Fourier series: a simple code to do the expansion

Curso: Física Matemática I
Prof. Davi C. Rodrigues
Departamento de Física, 
Universidade Federal do Espírito Santo

A simple and straightforward program to evaluate the Fourier series coeficients and the partial sum of the series. This program aims to solve analytical problems on Fourier Series. For numerical evaluation, some simple modifications can drastically improve performance.

The user should define the function, named f[x], and define the interval in which it should be considered (Linf,Lsup).

f[x_] = 3 Abs[x] + 1;  

Linf = -1;  
Lsup = 1;

$Assumptions = {n ∈ Integers, n >0, x ∈ Reals}; (*These assumptions are relevant for the simplifications.*)
 SetOptions[Plot, {AspectRatio-> 1, PlotTheme->"Detailed" , ImageSize->Large}]; (*Set graphical display options for the Plot command.*)

L = ((Lsup - Linf)/2);

 a0 = (1/L) Simplify[Integrate[ f[x] , {x,Linf,Lsup}]];

 a[n_] = (1/L) Simplify[Integrate[ f[x] Cos[((n π x)/L)], {x,Linf,Lsup}]];

 b[n_] = (1/L) Simplify[Integrate[ f[x] Sin[ ((n π x)/L)], {x,Linf,Lsup}]];

FourierS[m_,x_] =Simplify[(a0/2) + (∑_(n=1)^m)(a[n]Cos[ ((n π x)/L)] + b[n] Sin[((n π x)/L)])];  (*FourierS[∞,x] is the Fourier Series. FourierS[m,x] is its partial sum up to m.*)

The answers appear in the same order that the functions below are called

a0

a[2]

a[3]

a[n]

a0

a[n]

b[n]

Simplify[FourierS[1,x]]

FullSimplify[FourierS[1,x]]

FourierS[n,x]

f50[x_] = FullSimplify[FourierS[50,x]]

Plot[{1 - f[x]/f50[x]}, {x,-1,1}, PlotRange -> All, FrameStyle-> Large]

Plot[{ FourierS[1,x], FourierS[5,x],FourierS[20,x], f[x]}, {x,-1.5,1.5}, FrameStyle->  Large]

Plot[{ FourierS[1,x], FourierS[5,x],FourierS[20,x], f[x]}, {x,-3,3}, FrameStyle->  Large, PlotRange->{Automatic, {0,5}}]