Another example of expansion in (L^2)[-π,π]

Computing expansion coefficients using the inner product

First, define the function we want to expand:

f[x_]=Piecewise[{{-1,-Pi<x<0},{1,0<x<Pi}}]

Plot to make sure we've got it right:

Plot[f[x],{x,-Pi,Pi},
Ticks->{Range[-Pi,Pi,Pi/2],Range[-1,1]}]

Compute inner product of f and (Subscript[v, k])(x)=sin(k x):

fdotv=Integrate[f[x] Sin[k x],{x,-Pi,Pi},Assumptions->Element[k,Integers]]

Compute inner product of (Subscript[v, k])(x)=sin(k x) with itself:

vdotv=Integrate[ Sin[k x]^2,{x,-Pi,Pi},Assumptions->Element[k,Integers]]

Define the expansion coeffients:

a[k_]=fdotv/vdotv

Look at a list of these:

Table[a[k],{k,1,9}]

Create a manipulation to look at partial sums.  The manipulation variable is the number of terms included in the partial sum.  (Note that when you change the value of n, Mathematica first returns a quick and sometimes crude picture but continues to calculate a refinement behind the scenes.  You can tell this is happening because the cell bracket on the right side of the window is highlighted.  If you wait, Mathematica will update the plot with a refined picture.  This effect is particularly noticable here when you get to large values of n.

Manipulate[
Plot[{f[x],Sum[a[k]Sin[k x],{k,1,n}]},{x,-Pi,Pi},
PlotRange->{-1.5,1.5},
 ImageSize->Large],{n,1,201,2}]

Estimating expansion coefficients by minimizing mean-square error

The first manipulation here shows f and (Subscript[a, 1])sin(x) with the first expansion coefficient (Subscript[a, 1]) as the manipulation variable.  The plot also shows the value of the mean-square error (∫_(-π)^π)(((f(x)-(∑_(k=1)^n)(Subscript[a, k])sin(k x)))^2)dx.  Play with the value of (Subscript[a, 1]) to minimize the mean-square error.  Compare the value you get here with the value computed above.

Manipulate[
Show[
Plot[{f[x],a1*Sin[x]},{x,-Pi,Pi},PlotRange->{-1.5,1.5},ImageSize->Large],
Graphics[
{Text[Style[NumberForm[NIntegrate[(f[x]-a1*Sin[x])^2,{x,-Pi,Pi}],{5,4}],Larger],{2,-1}],
Text["mean-square error:",{2,-0.875}]}
]
],
{{a1,0},-2,2}]

Now set (Subscript[a, 1])=4/π and add a second term.  We skip over (Subscript[a, 2])sin(2 x)  since (Subscript[a, 2]) turns out to be 0.  So, the new term we include is (Subscript[a, 3])sin(3 x) and we let (Subscript[a, 3]) be the manipulation parameter.  Try to minimize the mean-square error with this new term included.

Manipulate[
Show[
Plot[{f[x],4/Pi*Sin[x]+a3*Sin[3x]},{x,-Pi,Pi},PlotRange->{-1.5,1.5},ImageSize->Large],
Graphics[
{Text[Style[NumberForm[NIntegrate[(f[x]-4/Pi*Sin[x]-a3*Sin[3x])^2,{x,-Pi,Pi}],{5,4}],Larger],{2,-1}],
Text["mean-square error:",{2,-0.875}]}
]
],
{{a3,0},-2,2}]