I'm having a lot of trouble with functions build from other functions. I'm struggling to understand the nuance of variable replacement. Here is an example:

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

p3[x_, l_, m_] = p2[x, l, m] * 1;

The p2 equation works, for example: p2[x, 2, 1] $-3x\sqrt{1-x^2}$, and p2[1/2, 2, 1] $=-\frac{1}{4} \left(3 \sqrt{3}\right)$.

But the second equation doesn't work, p3[1/2, 2, 1] gives the error: General::ivar: 1/2 is not a valid variable.

The second equation only works if I replace $x$ afterwards. p3[x, 2, 1] /. x -> 1/2 $=-\frac{1}{4} \left(3 \sqrt{3}\right)$. I don't understand this behavior.

  • 1
    $\begingroup$ Use SetDelayed instead of Set. That is, add a colon: p3[x_, l_, m_] := p2[x, l, m] * 1; $\endgroup$
    – Domen
    Aug 20 '21 at 15:48

Your troubles comes from the derivative. To do away with not relevant factors, define p2 as:

p2[x_, l_, m_] := (D[(y^2 - 1)^l, {y, l + m}]) /. y -> x

By using "Set" and not "SetDelayed" you are evaluating p3 at once. By specifying p3[x_, l_, m_] = p2[x, l, m] * 1; you actually evaluate p2 with unknown variables x,l,m. This results in:

enter image description here

This means: take the (1+m) th derivative of (-1+x^2)^l relative to x.

If you now call p3[1/2, 2, 1] you replace x by 1/2, l by 2 and m by 1, resulting in

This means derive 9/16 relative to 1/2 three times, what is nonsense.

On the other hand, if you use "SetDelayed", specifying:

p3[x_, l_, m_] := p2[x, l, m]*1;

p2 is only evaluate when x,l, and m are known and x,l and m are replaced by their numerical values before p2 is evaluated. The derivative now reads:

enter image description here

what makes sense.

  • $\begingroup$ It's still strange to me. P2 is defined as set-delayed, so why would defining p3 as set override that? The derivative in P2 is done with dummy variable Y, is p3 ignoring that? $\endgroup$
    – Frank
    Aug 21 '21 at 14:50
  • 1
    $\begingroup$ "SetDelayed" means: evaluate when called. If you define p3 using "Set", then p3 is evaluated when defined. But this means, that p2 is called and the symbolic x,l,m from p2 are replaced (or evaluated) to the symbolic x,l,m of p3. Further, the derivative is not done as long as m is symbolic. But then you replace y by x. And this x is then replaced by 1/2. You ay get a bit more info by using Trace $\endgroup$ Aug 22 '21 at 14:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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