(* This notebook is designed to compute the Fourier series for a given function (in this case, a triangular wave). We'll plot the function, construct the Fourier series, and then plot the series with various numbers of terms so we can analyze the convergence. Created by Scott LaLonde, 5/12/2014. *)

(* Plot the triangle wave. We've shifted and scaled the wave to get something a little more interesting. *)
T[x_]=2*TriangleWave[x/4-5/4]+2;
Plot[T[x], {x, -6, 6}, AspectRatio->0.4]

(* Construct the Fourier series for T. Plot the first term. *)
F[x_]=2-(16/Pi^2)*Sum[1/(2*n-1)^2*Cos[(2*n-1)*Pi/2*x],{n,1,1}];
Plot[{F[x], T[x]},{x, -6, 6}, AspectRatio->0.4]

(* That looks pretty good. How about 2 terms? *)
F[x_]=2-(16/Pi^2)*Sum[1/(2*n-1)^2*Cos[(2*n-1)*Pi/2*x],{n,1,2}];
Plot[{F[x], T[x]},{x, -6, 6}, AspectRatio->0.4]

(* 5 terms. Looks pretty good. *)
F[x_]=2-(16/Pi^2)*Sum[1/(2*n-1)^2*Cos[(2*n-1)*Pi/2*x],{n,1,5}];
Plot[{F[x], T[x]},{x, -6, 6}, AspectRatio->0.4]

(* Let's switch gears and look at the square wave. The convergence is a little trickier. *)
S[x_]=SquareWave[x/(2*Pi)];
Plot[S[x], {x, -2Pi, 2Pi}]

(* Construct the Fourier series. Plot first term. *)
G[x_]=2/Pi*Sum[(1-(-1)^n)/n*Sin[n*x], {n, 1, 1}];
Plot[{S[x], G[x]}, {x, -2Pi, 2Pi}]

(* Not great. Let's do 3 terms. *)
G[x_]=2/Pi*Sum[(1-(-1)^n)/n*Sin[n*x], {n, 1, 3}];
Plot[{S[x], G[x]}, {x, -2Pi, 2Pi}]

(* 10 terms. *)
G[x_]=2/Pi*Sum[(1-(-1)^n)/n*Sin[n*x], {n, 1, 10}];
Plot[{S[x], G[x]}, {x, -2Pi, 2Pi}]

(* 40 terms. *)
G[x_]=2/Pi*Sum[(1-(-1)^n)/n*Sin[n*x], {n, 1, 40}];
Plot[{S[x], G[x]}, {x, -2Pi, 2Pi}]

(* Now we'll put in a slider that will let us vary the number of terms from 1 to 150. This will let us analyze the convergence of the Fourier series. *)
Manipulate[Plot[{S[x],2/Pi*Sum[(1-(-1)^i)/i*Sin[i*x], {i,1, a}]}, {x, -2Pi, 2Pi},PlotRange->{{-2Pi,2Pi},{-1.5,1.5}}],{a,1,150}]