2

I am trying to calculate deriv of a complicated function and store the values for reuse. But the FullSimplify in my definition doesn't seem work all the time:

Clear[dpdx, m];
gau[x_, v_] = (1/Sqrt[2*Pi*v])*E^-((x^2)/(2*v));
dpdx[n_] := dpdx[n] = FullSimplify[D[gau[-x, v], {x, n}]/gau[-x, v]];

ord = 4;
g = Log[p[x, v]];
h1 = Table[D[g, {x, i - 1}], {i, 1, ord}];
h = h1 /. Derivative[q_, r_][p][x, v] -> dpdx[q + 2*r]/(2^r);
Print[h // MatrixForm];
Print[h1 // MatrixForm];

The FullSimplify should cancel out all of the exponentials, but it only cancels them when q=1 and leave the others. Expand and Simplify fail too.

Even more puzzingly, if I just call for a value like dpdx[10], the FullSimplify works perfectly. Help?

Jerry Guern
  • 4,602
  • 18
  • 47

1 Answers1

6

The answer has to do with the difference between Rule(->) and RuleDelayed(:>):

Rule:

h = h1 /. Derivative[q_, r_][p][x, v] -> dpdx[q + 2*r]/(2^r)

RuleDelayed:

h = h1 /. Derivative[q_, r_][p][x, v] :> dpdx[q + 2*r]/(2^r)

Rule a -> b first evaluates the expression b and then replaces a with b. RuleDelayed a :> b first replaces a with b, holds the expressions in b unevaluated and then evaluates b.

In your case, if just Rule (->) is applied:

dpdx[q + 2*r]/(2^r)

its directly evaluated to

2^(1/2 - r)*E^(x^2/(2*v))*Sqrt[Pi]*Sqrt[v]*
 D[1/(E^(x^2/(2*v))*Sqrt[2*Pi]*Sqrt[v]), {x, q + 2*r}]

In this step the FullSimplify allready has been applied to the expression. But v and r where still symbolic and could not have been more simplified. RuleDelayed first puts in the values of v and r, evaluates this expression, and replaces the full simplified expression.

EDIT:

You can actually see the difference by the colloring of variables in the Mathematica FrontEnd. With x_ -> Simplify[x], the right side x is collored blue, wich means that its global, not protected from evaluation. It just evaluates to x_-> x, since Simplify[x] is just x.

With x_ :> Simplify[x] the x on the right side of the rule is collored in green, like the pattern itself, wich means, that its treated kind of a local variable inside of the rule, protected from evaluation untill the rule has been applied.

enter image description here

I remember, when i first understood the difference, it also took me a while to realize, but after the "penny drops" its clear and very usefull to know.

sacratus

sacratus
  • 1,556
  • 10
  • 18