Fourier Series Examples

Fourier Series for Box function on [0,π]

f[x_]:=Piecewise[{{1,π/4<x<3*π/4},{0, 0<x<π/4},{0,3*π/4<x<π}}]

Plot[f[x],{x,0,π},PlotStyle->Thickness[.01],PlotRange->All,AxesLabel->{"x","f(x)"},LabelStyle->Directive[Bold, Black,Medium],AxesStyle->Directive[Black, 12]]

Calculation of Fourier Coefficients

2/π*Integrate[f[x]*Sin[n*x],{x,0,π},Assumptions->n∈Integers]

b[n_]:=((4 Sin[((n π)/4)] Sin[((n π)/2)])/(n π));
g[x_,m_]:=Sum[b[n]*Sin[n*x],{n,1,m}];

Plot[{g[x,1],g[x,5],g[x,10],g[x,20],g[x,40],g[x,80],f[x]},{x,0,π},PlotStyle->Thickness[.01],PlotRange->All,AxesLabel->{"x","f(x)"},LabelStyle->Directive[Bold, Black,Medium],AxesStyle->Directive[Black, 12]]

Animate[Plot[{g[x,m],f[x]},{x,0,π},PlotStyle->Thickness[.01],PlotRange->{-.3,1.3},AxesLabel->{"x","f(x)"},LabelStyle->Directive[Bold, Black,Medium],AxesStyle->Directive[Black, 12]],{m,1,100}]

Spectrum Diagram

kmax=12;
plot1=ParametricPlot3D[{x,0,f[x]},{x,0,π},PlotStyle->Thickness[.01],PlotRange->{{0,π},{0,kmax},{-.3,1.3}},AxesLabel->{"x","k"},LabelStyle->Directive[Bold, Black,Medium],AxesStyle->Directive[Black, 12],Boxed->False];
For[n=1,n≤kmax,
plot2=ParametricPlot3D[{x,n,b[n]*Sin[n*x]},{x,0,π},PlotStyle->{ColorData["Rainbow"][1-n/kmax],Thickness[.01]},PlotRange->{{0,π},{0,kmax},{-.3,1.3}},AxesLabel->{"x","k"},LabelStyle->Directive[Bold, Black,Medium],AxesStyle->Directive[Black, 12],Boxed->False];
plot1=Show[plot2,plot1];
n++];
Show[plot1]