Expansion of function in Legendre polynomials

First, define the function you want to expand in Legendre polynomials. Here, the variable x = cos (θ) is used instead of the original θ. Recall our original function is f(θ) = (cos^4)θ + (sin^2)θ + sin θ.

f[x_]:=x^4 + (1-x^2) + Sqrt[1-x^2]

It is always a good idea to plot your function. This will help you see if the function is even, odd, or neither.

Plot[f[x],{x,-1,1},PlotStyle->Directive[Thick]]

Our function ic clearly even (i.e., f(x)=f(-x)). Now write the code that computes the coefficient (Subscript[A, l]) for a Legendre polynomial of order l. The "PrecisonGoal" switch just says we want our result to be accurate to 6 significant figures.

lpcoeff[f_,l_]:=NIntegrate[((2l+1)/2)f[x] LegendreP[l,x],{x,-1,1},PrecisionGoal->6]

Compute a list of coefficients that multiply the first 6 even Legendre polynomials. Remember that since our function is even, we have no odd orders so we do not waste time computing them:

Table[lpcoeff[f,l],{l,0,10,2}]

Now write the code that generates the actual series expansion for our function. Since our function is even, we skip the odd orders.

lpseries[f_,M_,x_]:=Sum[lpcoeff[f,l]LegendreP[l,x],{l,0,M,2}]

Calculate the expansion using the Legendre polynomials of even order up to and including order 6.

lpseries[f,6,x]

The coefficients multiplying the polynomials in this expansion are the product of the coefficients computed above and the factors that multiply properly normalized Legendre polynomials, which is why the coefficients here don't seem to match the ones computed above. Now plot both the original function and our Legendre polynomial expansion to see how well the match is. The original function is blue. Notice how similar the two plots are just using a few polynomials. Not bad:

Plot[{f[x],lpseries[f,6,x]},{x,-1,1}, PlotStyle->Directive[Thick]]