Why Does Mathematica Output Unexpected Results with Derivative Rules?

  • Context: Mathematica 
  • Thread starter Thread starter unih
  • Start date Start date
  • Tags Tags
    Mathematica
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 2K views
unih
Messages
27
Reaction score
0
Hi!
Please help the idiot
In[] = D[p[x,t],x,t]/.{Derivative[n_,m_][p_][q__]->a^(n+m)}
Out[] = a2

In[] = D[p[x,t],x,t]/.{Derivative[n__][p_][q__]->a^Plus[n]}
Out[] = a

WTF? Why not a2?

In the simplest case
In[] = D[p[x,t],x,t]/.{Derivative[n__][p_][q__]->Plus[n]}
Out []=Sequence[1, 1]

In[] = D[p[x,t],x,t]/.{Derivative[n__][p_][q__]->Plus[n,1]}
Out []= 3
Works!

In[] = D[p[x,t],x,t]/.{Derivative[n__][p_][q__]->(Plus[n,1]-1)}
Out []= Sequence[1, 1]
What hell is going on?

Thank you very much!
 
Last edited:
Physics news on Phys.org
It's because you are using Rule instead of RuleDelayed.
This means that the right-hand-side of the rule gets evaluated before you want it to.
So Plus[n] gets turned into n before n gets replaced with anything. The rule then fires n gets replaced with Sequence[1,1] explaining your last line.

Everything works as you want if you use
Derivative[n__][p_][q__] :> a^Plus[n]
instead of you original
Derivative[n__][p_][q__] -> a^Plus[n]

Another option would be
Derivative[n_,m___][p_][q__] :> a^Plus[n,m]
which would still work in the case of
Derivative[n__][p_][q__] -> a^Plus[n]

The place where the use of Rule instead of RuleDelayed becomes really problematic is if a term on the RHS already has a value. For example, compare the output of
n = 5;
D[p[x, t], x, t] /. {Derivative[n__][p_][q__] -> a^Plus[n]}
with
n = 5;
D[p[x, t], x, t] /. {Derivative[n__][p_][q__] :> a^Plus[n]}
From version 6 and above, Mathematica has syntax highlighting, so you can tell whether a variable is defined, undefined or localized by its color (black, blue or green respectively).
 
Thank you VERY VERY MUCH! I have no words to tell how you helped me