To see why Mathematica does what it does, it can be instructive to write out the FullForm
of the expressions in question. This tells you how Mathematica is storing these things internally.
FullForm[rule]
(* List[Rule[Times[a,Power[b,-1]],c]] *)
So what Mathematica is doing when it applies rule
is replacing all internal instances of Times[a, Power[b, -1]]
with c
. Notably, it will not replace sub-expressions that do not literally match this expression.
If we look at Fullform[eq]
, we can see why some of the expressions get replaced and others don't:
FullForm[eq]
(* Plus[
Times[Power[a,2],Power[b,-2]],
Times[a,Power[b,-1]],
Times[Power[a,-1],b],
Times[Power[a,-2],Power[b,2]],
Power[E,Times[a,Power[b,-1]]],
Log[Times[a,Power[b,-1]]]
] *)
From this, you can see that three of the summands in eq
actually contain the literal expression Times[a,Power[b,-1]]
, and so Mathematica replaces those with c
. In contrast, the other three summands do not contain this expression and so Mathematica leaves them alone when rule
is applied.
In contrast, if you define rule2 = {a -> c*b}
, as suggested by user64494, then internally Mathematica views this rule as
List[Rule[a,Times[b,c]]]
which means that it will replace the expression a
with Times[b,c]
everywhere it occurs. This gets all of the a
expressions, even those embedded inside other expressions involving Times
, Power
, etc. This is why it's general best to write replacement rules with a single symbol on the left-hand side; if you have a more complicated expression on the left-hand side, you're not guaranteed that Mathematica will replace everything you want it to replace.
Alternately, applying Hold
to an expression (as suggested by cvgmt prevents Mathematica from doing internal "simplification" and keeps things in the same form you literally entered them:
holdeq = Hold[1/(a/b)^2 + (a/b)^2 + 1/(a/b) + a/b + Exp[a/b] + Log[a/b]];
FullForm[holdeq]
(* Hold[
Plus[
Times[1,Power[Power[Times[a,Power[b,-1]],2],-1]],
Power[Times[a,Power[b,-1]],2],
Times[1,Power[Times[a,Power[b,-1]],-1]],
Times[a,Power[b,-1]],Exp[Times[a,Power[b,-1]]],
Log[Times[a,Power[b,-1]]]
]
] *)
With the Hold
present, Mathematica does not apply any simplification rules, leaving the expression Times[a,Power[b,-1]]
in its original form; and so when rule
is applied, it successfully replaces all of the instances.