Since I had a similar problem same problem some time ago I'd like to expand on the other answers why mathematica does not simplify the expressions with the initial second attempt. ReplaceAll
(/.
) does not hold its arguments. That means both arguments will be evaluated before any replacements are performed.
The left hand side of /.
after evaluation can be found with
Sin[Sqrt[x + y]]/Sqrt[x + y] // FullForm
which gives
Times[Power[Plus[x,y],Rational[-1,2]],Sin[Power[Plus[x,y],Rational[1,2]]]]
Note the -1
which represents the inverse of the square root. The FullForm
of the pattern after evaluation is.
Power[Plus[x,y],Rational[1,2]]
The pattern is clearly different from the expression in the pattern and hence mathematica will (correctly) not replace it.
Multiple suggestions have already been given how to obtain the desired result. I'd like to give two more suggestions.
Unevaluated
One could wrap both sides in Unevaluated
which will shield them from evaluation before replacement is performed.
Unevaluated[Sin[Sqrt[x+y]]/Sqrt[x+y]]/.Unevaluated[{Sqrt[x + y] -> z}]
this gives the desired result
Sin[z]/z
To see the difference to the first attempt use FullForm
on the Uneavlated
expression.
Pattern matching
My second attempt would be to improve on the pattern matching. Inspect that according to the output of the first equation the square root can also be written as Power[Plus[x, y], Rational[n_, 2]]
with n_
replaced by either -1
or 1
.
We will now use a slightly different right hand side of /.
which contains the pattern n_
to match both expressions on the evaluated left hand side
Sin[Sqrt[x+y]]/Sqrt[x+y] /. Power[Plus[x,y],Rational[n_,2]] :> Power[z,n]
which again gives the desired output Sin[z]/z
.
In conclusion pattern matching and non-standard evaluation can be very helpful features of mathematica. Especially non-standard evaluation is often essential to understand results which look quirky at first glance.
FullForm[Sqrt[x+z]]
andFullForm[1/Sqrt[x+z]]
. These show the actual expressions you are trying to transform, not the typeset version that you see in the Front End. $\endgroup$Sqrt[..]
, so sometimes I paste an image of the output when I want to show the typeset form. The principal point of the link is that making input copy-pasteable is a convenience to others that invites their help. $\endgroup$