To replace a single variable by another variable, one can simply use the the replace all (/.
) operator (e.g., x/(y*z) /. x -> w
returns $\displaystyle \frac{w}{yz}$).
How does one replace an expression consisting of multiple variables? Trying to replace the denominator in the previous expression by a single variable fails with the following syntax:
x/(y*z) /. y*z -> w
x/(y*z) /. y*z :> w
x/(y*z) /. (y*z) -> w
x/(y*z) /. (y*z) :> w
x/(y*z) /. Times[y, z] -> w
x/(y*z) /. Times[y, z] :> w
Edit: By applying FullForm
, I see that the variable substitution can be made by the following lengthy expression:
x/(y*z) /. Times[Power[y, -1], Power[z, -1]] -> w^-1
However, this now fails in a case such as the following:
(x + Log[y*z])/(y*z) /. Times[Power[y, -1], Power[z, -1]] -> w^-1
Now one must use something like the following (which does not work).
(x + Log[y*z])/(y*z) /. {Times[Power[y, -1], Power[z, -1]] -> w^-1, Times[y, z] -> w}
Is there a more general way to replace variables with delving into the full form representation?
Answer
You can't use replacements that way, because Mathematica does not do replacements on expressions the way they appear to you. To see what I mean, take a look at the FullForm
of your expression:
x/(y*z) // FullForm
Out[1]= Times[x,Power[y,-1],Power[z,-1]]
Whereas, the replacement that you're using is Times[y, z]
.
In general, it is not a good idea to use approaches that exploit the structure of expressions to do mathematical replacements. You might think you have nailed the replacement down, but it will break for a slightly different equation or terms.
To do this in a fail safe manner, you can use Simplify
as:
Simplify[x/(y z), w == y z]
Out[2]= x/w
For more complicated examples, you might have to use Eliminate
. From the documentation:
Eliminate[{f == x^5 + y^5, a == x + y, b == x y}, {x, y}]
Out[3] = f == a^5 - 5 a^3 b + 5 a b^2
Also read the tutorial on eliminating variables.
Comments
Post a Comment