Section 3.2 Problem 3

To save typing later, start by defining our own function to compute the integral that is the inner product here:

inner[f_,g_]:=Integrate[f*g,{x,-1,1}]

Check that our definition works for some simple cases we can easily do by hand:

inner[1,x]

inner[1,1]

Name our original polynomials:

u0=1
u1=x
u2=x^2
u3=x^3

Compute some inner products to confirm that these original polynomials are not orthogonal:

inner[u0,u1]

inner[u0,u2]

Gram-Schmidt to produce an orthogonal set:

v0=u0

v1=u1-inner[u1,v0]/inner[v0,v0]*v0

v2=u2-inner[u2,v0]/inner[v0,v0]*v0-inner[u2,v1]/inner[v1,v1]*v1

v3=u3-inner[u3,v0]/inner[v0,v0]*v0-inner[u3,v1]/inner[v1,v1]*v1-inner[u3,v2]/inner[v2,v2]*v2

For convenience, name the function we will be expanding:

f[x_]=Exp[x]

Compute the expansion cofficients:

a0=inner[f[x],v0]/inner[v0,v0]

a1=inner[f[x],v1]/inner[v1,v1]

a2=inner[f[x],v2]/inner[v2,v2]

a3=inner[f[x],v3]/inner[v3,v3]

To get a better feel for these coefficients, look at them in decimal form:

N[{a0,a1,a2,a3}]

Now plot f together with the approximation:

Plot[{f[x],a0*v0+a1*v1+a2*v2+a3*v3},{x,-1,1}]

In the above plot, it's hard to see a difference between the two so plot the absolute value of the difference (i.e., the pointwise error):

Plot[Abs[f[x]-(a0*v0+a1*v1+a2*v2+a3*v3)],{x,-1,1}]

In terms of error, the most relevant measure is the mean-square error:

Integrate[(f[x]-(a0*v0+a1*v1+a2*v2+a3*v3))^2,{x,-1,1}]

N[%]

Mathematica has a built-in definition for Legendre polynomials:

LegendreP[2,x]

Here's the first 11:
(Note the //TableForm below affects the formatting of the output.)

Table[LegendreP[n,x],{n,0,10}]//TableForm

Plot[Table[LegendreP[n,x],{n,0,4}],{x,-1,1}]