2

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

NBur
  • 159
  • 3
  • 10
  • in your post there is no question mark. So what is your question? Do you want to avoid the discontinuities being connected by straight lines? – theozh Feb 11 '19 at 14:02
  • The question is “why the green curve doesn't match the pink one?” – NBur Feb 11 '19 at 14:50

1 Answers1

2

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)
Ethan
  • 13,715
  • 2
  • 12
  • 21
  • that's really one of the meanest gnuplot pitfalls: "unexpected" integer division. I know, some programming languages do the same thing. But I really would love to see `/` as floating point division in gnuplot and if possible maybe `//` as integer division. – theozh Feb 11 '19 at 18:57
  • And that was as simple as this… Thanks a lot: I was far of thinking about integer division. – NBur Feb 12 '19 at 07:35