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?
Integrate
from -1 to 1 by usingIntegrate[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. $\endgroup$f[1]-f[-1]
" and I'll accept) $\endgroup$