#---------------------------------------------------  
# Somma di onde sinusoidali 
# - Onda arbitraria 4, animazione a  
#
#  GdA, aprile 2023
#
#----------------------------------------------------

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

# ampiezza e fase delle varie armoniche
A.cos    <- function(k) 2/(k*pi) * sin(k*pi*par)
phi.cos  <- function(k) return(0)   # (k-1)/2 * pi

T    <- 1         # s
par <- 0.3                # 'parametro extra'
om0 <- 2*pi/T              # pulsazione fondamentale  
arm.max <- 100              # armonica massima (1,3,5,...)
n <- floor((arm.max-1)/2)

t <- seq(-0.75,1.25,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, phi.cos/pi = %.0f\n",
                    k, A.cos(k), phi.cos(k)/pi ))        
        fk <- A.cos(k)*cos(k*om0*t +  phi.cos(k))        
        f  <- f + fk
        plot(t, fk, ty='l', lty=2, col='blue',
             xlab='t / T', ylab='f(t)', ylim=c(-1.1,1.1)*A.cos(1))        
        abline(h=0)        
        points(t, f, ty='l', lty=1, lwd=2, col='blue')
        testo <- sprintf("k = %d", k)
        text(0,-0.25, testo, cex=2, col='magenta')
        if(k<4)  {
            pausa()
        } else {
            Sys.sleep(0.01)
        }
    }    
}
