# Non-Convergence In Creating Legendre Series

I'm trying to use Mathematica to create a Legendre-Fourier series using this Wikipedia article. Here is my code:

N1=1;
degree=10;

Fun=(-(N1^2 x) + (2 N1^2 x ArcTan[10000 N1^2 x])/Pi)/2;
Coefs=ConstantArray[0,degree];

For[i=0,i<degree,i++,
Legendre=LegendreP[i,x];
f[x_]=Integrate[Fun*Legendre,x];
Coefs[[i+1]]=N[(2*i+1)/2 * f[1]-f[-1]] ;]

LegendreSeries[x_]=Sum[Coefs[[i+1]]*LegendreP[i,x],{i,0,degree-1}];

Plot[{LegendreSeries[x],(-(N1^2 x) + (2 N1^2 x ArcTan[10000 N1^2 x])/Pi)/2},{x,-1,1}]


However, when I went to plot it side-by-side with the original function, even at degree=10, the series fails to converge.

I feel like I did something wrong, but I can't tell what. Could someone help me out?

• You should Integrate from -1 to 1 by using Integrate[Fun*Legendre,{x,-1,1}]. You are not checking the continuity of the antiderivative in your method. Moreover, you seems to be missing parenthesis () in one place. Sep 6, 2020 at 21:58
• @yarchik Thank you for the help. However, my function is smooth, so the integral should be continuous. Also, where did I leave out the parenthesis? (EDIT: Oh, I see it now. Silly me.) (EDIT 2: It works now! Could you just write up a quick answer along the lines of "You forgot a parenthesis around f[1]-f[-1]" and I'll accept) Sep 6, 2020 at 22:52
• @yarchik Also, one last question: can I make it so LegendreSeries[0] must be 0? Sep 6, 2020 at 23:09

## 1 Answer

N1 = 1;
degree = 20;

Fun = 1/2 (-(N1^2 x) + (2 N1^2 x ArcTan[10000 N1^2 x])/π)

al = Table[Integrate[Fun*LegendreP[l, x], {x, -1, 1}]/Integrate[LegendreP[l, x]^2, {x, -1, 1}], {l, 0, degree}];

fn[x_] := N[Sum[al[[l + 1]]*LegendreP[l, x], {l, 0, degree}]]

Plot[{fn[x], 1/2 (-(N1^2 x) + (2 N1^2 x ArcTan[10000 N1^2 x])/\[Pi])}, {x, -1, 1}]


• Thanks! A question: Is there a way so that LegendreSeries[0] must be 0? Sep 6, 2020 at 23:52
• You have a very sharp change in slope there, which is hard for a Fourier series to match exactly. You will get closer with higher values for degree. Sep 6, 2020 at 23:55
• Ok, thanks! +1 and accept! Sep 6, 2020 at 23:57
• You can still integrate from $-1$ to $0$ as for $x>0$, $f(x)=0$. Right? Jun 17, 2023 at 18:40
• @TymaGaidash you can get away with that for the numerator of a1 since Fun is very close to zero for $x>0$, but the denominator must include the entire integral limits. Try it. Jun 17, 2023 at 23:35