gnuplotcontinuous-fourier

plot Fourier expansion with gnuplot


After computing the Fourier coefficients of my function, I'd like to plot the first terms of the serie. However, I can't get the correct result…

It's not a matter of wrong coefficients as it plots correctly https://www.desmos.com/calculator/dh84khkc1o With the gnuplot code below

set terminal pngcairo
set output 'Fourier.png'
set samples 2000;

aa = -pi/2;
bb = pi/2;
repete(x) = (x-(bb-aa)*floor((x-aa)/(bb-aa)));
ff(x) = (-pi/2<x) && (x<0) ? x-cos(x)+1 : ((0<=x) && (x<pi/2)) ? x+cos(x)-1: 0;
fourier(k, x) = ((1-pi/2)*((-1)**k)+1/(4*k**2-1)) * sin(2*k*x) / k;

plot ff(repete(x)), 2/pi*sum [k=1:50] fourier(k,x)

I've got the discontinuities, but the “cos” part become a straight line.

enter image description here


Solution

  • Because the "k" in your invocation of fourier(k,x) is the index variable of the iterator [k=1:50], it is an integer. The fourier function, however, is expecting a real. Your plot is fixed by amending the plot command to

     plot ff(repete(x)), 2/pi*sum [k=1:50] fourier(real(k),x)