#---------------------------------------------------  
# Somma di onde sinusoidali
# - Onda arbitraria 2, animazione b   
# 
#  GdA, aprile 2023
#
#----------------------------------------------------

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

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

T  <- 1         # s  (periodo fondamentale)
om0 <- 2*pi/T   # pulsazione fondamentale
n   <-  100     # numero di armoniche  
y.lim <- c(-1.0, 1.3)        # limite plot

t <- seq(-1,1,len=10001)
f <-rep(0, length(t)) 
for(k in 1:n) {    
    cat(sprintf("k = %d,  A.cos = %.2e, phi.cos/pi = %.0f\n",
                k, a.k(k), phi.k(k)/pi ))
    fk <- a.k(k)*cos(k*om0*t +  phi.k(k))
    f  <- f + fk
    plot(t, fk, ty='l', lty=2, col='blue',             
         xlab='t / T', ylab='f(t)', ylim=y.lim)
    abline(h=0)
    points(t, f, ty='l', lty=1, lwd=2, col='blue')
    testo <- sprintf("k = %d", k)
    text(0,1, testo, cex=2, col='magenta')
    if(k<4)  {
        pausa()
    } else {
        Sys.sleep(0.01)
    }
}

