Inspired by a post in sage-devel (or support) group of SAGE, I came along with this few lines which allows me to plot a Fourier Series Approximation of the line, to a given order,

`sage: reset()`

sage: var('x,i,n')

(x,i,n)

sage: def b(n):

... return 2.*(-1)^(n+1)/n

...

sage: def f(x,n):

... return sum(b(i)*sin(i*x),i,1,n)

...

sage: p = Graphics()

sage: for n in [1,2,3,4,5,6]:

... p = plot(f(x,n), (x,-pi,pi), color=hue((n+1)/7.0)) + plot(x, -pi, pi, color='black') + text("Fourier Approximation of order %d" %n, (-1,3), fontsize=14, color='blue')

... p

...

and get as result, the series of plots that follows,

However, I was not happy ’cause I introduce the Fourier coefficients… So, I did a second try.

`sage: reset()`

sage: var('x,n,i')

(x,n,i)

sage: f(x) = x^2

`sage: def a(n):`

... coeff = integral(f(x)*cos(n*x), (x,-pi,pi))/pi

... return coeff

...

sage: def b(n):

... coeff = integral(f(x)*sin(n*x), (x,-pi,pi))/pi

... return coeff

...

sage: def FS(n):

... return a(0)/2 + sum(a(i)*cos(i*x)+b(i)*sin(i*x), i, 1, n)

...

Where I’ve defined the Fourier coefficients and the Fourier Series of a given function , introduced by the user.

With the line

`sage: for n in [1,2,3,4,5,6]:`

... p = plot(FS(n), (x,-1.1*pi,1.1*pi), color=hue((n+1)/7.0)) + plot(f(x), (x, -1.1*pi, 1.1*pi), color='black') + text("Fourier Approximation of order %d" %n, (0,-2), fontsize=14, color='blue')

... p

...

One get the Fourier Series Approximation for ,

#### NOTE…

**numerical_integrategral**command, but didn’t work. Does anyone knows why?

**range**command instead of a list for the loop… Didn’t work!!! Any clues?

Ok, that was it. Enjoy!!!

DOX.

on February 1, 2011 at 2:47 pm |Harald Schillynot tested, but instead of range, try srange. the numerical_integral probably needs a lambda function, is that the problem?

on February 2, 2011 at 7:51 am |doxdrumHi Schilly! Thank you for your comment.

I tried with srange and definitively it works… 🙂 THX.

I’ll try to implement the other suggestion later today. 😉

on February 1, 2011 at 9:10 pm |SAGE tip: Fourier Series Approximation with Interactive mode « Doxdrum's Blog[…] Comments « SAGE tip: Fourier Series Approximation […]