#---------------------------------------------------  
# 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)
f <- rep(0, length(t)) 
if(n>1) {
    for(i in 0: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
        plot(t, fk, ty='l', lty=2, col='blue',
             xlab='t / T', ylab='f(t)', ylim=c(-1,1)*0.5)        
        abline(h=0)
        points(t, f, ty='l', lty=1, lwd=2, col='blue')
        testo <- sprintf("k = %d", k)
        text(0,-0.2, testo, cex=2, col='magenta')
         if(k<20) {
            pausa()
        } else {
            Sys.sleep(0.2)
        }           
    }    
}
