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


Fun=(-(N1^2 x) + (2 N1^2 x ArcTan[10000 N1^2 x])/Pi)/2;

Coefs[[i+1]]=N[(2*i+1)/2 * f[1]-f[-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.

Legendre Fail

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

  • $\begingroup$ 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. $\endgroup$
    – yarchik
    Sep 6, 2020 at 21:58
  • $\begingroup$ @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) $\endgroup$
    – DUO Labs
    Sep 6, 2020 at 22:52
  • $\begingroup$ @yarchik Also, one last question: can I make it so LegendreSeries[0] must be 0? $\endgroup$
    – DUO Labs
    Sep 6, 2020 at 23:09

1 Answer 1

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}]

enter image description here

  • $\begingroup$ Thanks! A question: Is there a way so that LegendreSeries[0] must be 0? $\endgroup$
    – DUO Labs
    Sep 6, 2020 at 23:52
  • $\begingroup$ 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. $\endgroup$
    – Bill Watts
    Sep 6, 2020 at 23:55
  • $\begingroup$ Ok, thanks! +1 and accept! $\endgroup$
    – DUO Labs
    Sep 6, 2020 at 23:57
  • $\begingroup$ You can still integrate from $-1$ to $0$ as for $x>0$, $f(x)=0$. Right? $\endgroup$ Jun 17, 2023 at 18:40
  • $\begingroup$ @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. $\endgroup$
    – Bill Watts
    Jun 17, 2023 at 23:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.