#---------------------------------------------------  
# Onda triangolare ottenuta sommando onde sinusoidali
# 
#  GdA, aprile 2023
#
#----------------------------------------------------

pausa <- function() { cat ("\n >> press Enter to continue\n"); scan() }

# ampiezza e fase delle varie armoniche
A.cos <- function(k) 4/(k^2*pi^2)

T <- 1
om0 <- 2*pi/T              # pulsazione fondamentale
arm.max <- 19              # armonica massima (1,3,5,...)
n <- floor((arm.max-1)/2)

t <- seq(-2,2,len=10001)
k <- 1
fk <- A.cos(k)*cos(k*om0*t)
f  <- fk
plot(t, fk, ty='l', lty=2, col='blue',
     xlab='t / T', ylab='f(t)', ylim=c(-1,1)*0.5)
abline(h=0)
pausa()
if(n>1) {
    for(i in 1:n) {        
        k <- i*2 + 1        
        cat(sprintf("k = %d,  A.cos = %.2e\n", k, A.cos(k)))           
        fk  <- A.cos(k)*cos(k*om0*t)        
        f <- f + fk        
        points(t, fk, ty='l', lty=2, col='blue')        
        if(k<20) pausa()        
}
}
points(t, f, ty='l', lty=1, lwd=2, col='blue')
testo <- sprintf("kmax = %d", k)
text(0.5,0.5, testo, cex=2, col='magenta')
