Mathematica Why Does Mathematica Output Unexpected Results with Derivative Rules?

  • Thread starter Thread starter unih
  • Start date Start date
  • Tags Tags
    Mathematica
AI Thread Summary
The discussion revolves around the confusion experienced when using Mathematica's differentiation and replacement rules. The user initially encounters unexpected output when applying the differentiation function with a replacement rule. The key issue identified is the use of the Rule operator instead of RuleDelayed, which causes the right-hand side of the rule to evaluate prematurely. This leads to incorrect substitutions, as variables are evaluated before being replaced. The correct approach is to use RuleDelayed (":>") to ensure that the right-hand side is evaluated only after the left-hand side has been processed. Alternative methods, such as using a different pattern for derivatives, are also suggested. The conversation highlights the importance of understanding evaluation order in Mathematica to avoid similar issues in future computations.
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
 
Not a problem!
 

Similar threads

Back
Top