Feeds:
Posts

## SAGE tip: Fourier Series Approximation

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,

1st Fourier Approximation to a Line

2nd Fourier Approximation to a Line

3rd Fourier Approximation to a Line

4th Fourier Approximation to a Line

5th Fourier Approximation to a Line

6th Fourier Approximation to a Line

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 $f(x)$, 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 $f(x)=x^2$,

1st Approximation for the parabola

2nd Approximation for the parabola

3rd Approximation for the parabola

4th Approximation for the parabola

5th Approximation for the parabola

6th Approximation for the parabola

#### NOTE…

• The use of the last program is restricted to the interval $[-\pi,\pi]$.
• In order to find the Fourier coefficients the integrals might be doable… so no every function $f(x)$ can be shown as a Fourier series approximation.
• I tried to define the above using numerical_integrategral command, but didn’t work. Does anyone knows why?
• I also tried to use range command instead of a list for the loop… Didn’t work!!! Any clues?
• Ok, that was it. Enjoy!!!

DOX.

### 3 Responses

1. on February 1, 2011 at 2:47 pm | Reply Harald Schilly

not tested, but instead of range, try srange. the numerical_integral probably needs a lambda function, is that the problem?

• Hi 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. 😉

2. […] Comments « SAGE tip: Fourier Series Approximation […]