Please explain why in the following mathematica code, the cos term was not replaced in the first try, but got replaced in the second try?
g[x]/x Cos[x]
% /. {Cos[x] -> Integrate[Cos[x], x], g[x]/x -> D[g[x]/x, x]}
% /. Cos[x] -> Integrate[Cos[x], x]
Following is the output I am getting
(Cos[x] g[x])/x
Cos[x] (-(g[x]/x^2) + Derivative[1][g][x]/x)
Sin[x] (-(g[x]/x^2) + Derivative[1][g][x]/x)
What I tried:
The following code gives expected result
g[x] Cos[x]
% /. {Cos[x] -> Integrate[Cos[x], x], g[x] -> D[g[x], x]}
Output:
Cos[x] g[x]
Sin[x] Derivative[1][g][x]
I guess the 1/x factor is messing something up?
Extra points: Now, the following code (using :> instead of ->) does not work
g[x]/x Cos[x] /. {Cos[x] :> Integrate[Cos[x], x],
g[x]/x :> D[g[x]/x, x]}
Next, the following code each work. First, as suggested by @edinorog2196
, using g[x] -> x D[g[x]/x, x]
instead of g[x] -> x D[g[x]/x, x]
works
g[x]/x Cos[x] /. {Cos[x] -> Integrate[Cos[x], x],
g[x] -> x D[g[x]/x, x]}
Also using ReplaceRepeated (//.) (suggested by @BobHanlon and @RolandF) works, irrespective of using :> or ->:
g[x]/x Cos[x] //. {Cos[x] -> Integrate[Cos[x], x],
g[x]/x -> D[g[x]/x, x]}
g[x]/x Cos[x] //. {Cos[x] :> Integrate[Cos[x], x],
g[x]/x :> D[g[x]/x, x]}
ReplaceRepeated
(//.
) instead ofReplaceAll
(/.
) $\endgroup$1/x // FullForm
givesPower[x,-1]
$\endgroup$g[x] -> x D[g[x]/x, x]
. In my experience it is better to just substitute a single thing rather than an expressiong[x]/x
which could not be found in the code (you have(Cos[x]g[x])/x
) $\endgroup$Replace
documentation explains that when a list of rules is given, the result with the first rule that applies is returned. Your expected result is given byReplace Repeated
, which repeatedly performs replacements until the expression no longer changes. $\endgroup$