#---------------------------------------------------  
# Somma di onde sinusoidali
# - Onda arbitraria 1, 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^2
phi.k  <- function(k) return(0)

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

t <- seq(-2,2,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,-0.25, testo, cex=2, col='magenta')
    if(k<4)  {
        pausa()
    } else {
        Sys.sleep(0.01)
    }
}

