# Associated Legendre polynomials in Mathematica

I'm trying to look at the Associated Legendre Polynomial, so I plugged it into Mathematica to see the values for different input.

From wikipedia:

$$p_l(x)=\frac{1}{2^l l!}\frac{\partial ^l}{\partial x^l}\left(x^2-1\right)^l$$

$$p_l^m(x) = (-1)^m(1-x^2)^{m/2}\frac{\partial ^l}{\partial x^l}p_l(x)$$

But when I try to program this in Mathematica, I get a strange behavior (I think)

p[x_, l_, m_] = (-1)^m*(1 - x^2)^(m/2)*
D[1/(2^l l!)*D[(x^2 - 1)^l, {x, l}], {x, m}];


Above, what I think is the correct Associated Legendre Polynomial is zero for any value of m not equal to zero. Why?

I looked at just $$p_l(x)$$:

pl[x_, l_] = 1 / (2^l * l!) * D[(x^2 - 1)^l, {x, l}];
D[pl[2, 3], {x, m}]


When I took the derivative of $$p_l(x)$$ at $$x=2, L = 3$$ $$\begin{array}{cc} \{ & \begin{array}{cc} 17 & m=0 \\ 0 & \text{True} \\ \end{array} \\ \end{array}$$

This shows that it is zero for any value of $$m \neq 0$$. Is my code or the equation I am using wrong? Or should the derivative really be zero for any m?

• This is late, but it should be noted that LegendreP[] is built-in. Dec 11, 2021 at 16:23

You are evaluating the intermediate results too soon. Consider this simple example:

$$f_\ell(x) = \frac{\partial}{\partial x} x^\ell.$$

What is $$f_3(2)$$? To evaluate this, you first do the differentiation and then apply the $$x$$:

$$f_3(2) = \left(\frac{\partial}{\partial x} x^3\right)\bigg|_{x=2} = 3x^2\big|_{x=2} = 12.$$

You cannot do it like this:

$$f_2(3) = \frac{\partial}{\partial x} 3^2 = 0 \quad (?!)$$

But this is exactly what you do in the second code:

D[pl[2, 3], {x, m}]


First, pl[2, 3] is evaluated to a constant ($$17$$), whose derivative is then obviously zero.

One way to resolve this is to use a differently named "dummy" variable for differentiation:

pl[x_, l_] := 1/(2^l*l!)*D[(x^2 - 1)^l, {x, l}];
p[x_, l_, m_] := (-1)^m*(1 - x^2)^(m/2)*D[pl[y, l], {y, m}] /. y -> x;

p[x, 2, 1]
(* -3 x Sqrt[1-x^2] *)

p[1/2, 3, 1]
(* -((3 Sqrt[3])/16) *)

p[.2, 2, 2]
(* 2.88 *)


When plotting, don't forget to use Evaluate, otherwise $$P_m^l$$ will be unnecessarily recalculated for each plot point.

GraphicsGrid[Partition[
Table[Plot[
Evaluate[Table[LegendreP[l, m, x], {m, 0, l}]], {x, -1, 1},
PlotLegends -> Table[Subsuperscript["P", l, m], {m, 0, l}]], {l,
0, 3}], 2], ImageSize -> 500]


• I think I got it as:  pl[x_, l_] = 1/(2^l*l!)*D[(x^2 - 1)^l, {x, l}]; p[x_, l_, m_] = (-1)^m*(1 - x^2)^(m/2)*D[pl[x, l], {x, m}]; p[x, 3, 1];  But how to evaluate at say, x=2? Aug 19, 2021 at 14:52
• To evaluate the derivative at a point, you can use Replace: D[x^3, x] /. x -> 2 (* 12 *). Aug 19, 2021 at 15:44
• When I substitute after p[x,3,1] /. x -> 1/2 it works. But when I substitute in the equation it fails (General::ivar: 1/2 is not a valid variable.) Edit: It worked when I put the whole equation in parenthesis. Aug 20, 2021 at 14:25