Definition of a general rule

By defining:

rule = Sqrt[expr_^2] :> expr;

and writing:

Sqrt[x^2] /. rule

I get:

x

which is what is desired (regardless of formal correctness).

On the other hand, writing:

Sqrt[x^2 y] /. rule

I get:

Sqrt[x^2 y]

x Sqrt[y]

How can I generalize the above rule so that it also applies in the second case?

• I'm not sure how you would generalize, but Sqrt/@(x^2 y)/.rule gives the desired output. Feb 17 '20 at 13:35
• @user1066: Thank you! Unfortunately, without $y$, you don't get what you want.
– TeM
Feb 17 '20 at 13:46

rule = Sqrt[a_. * expr_^n_?EvenQ] :> expr^(n/2)*Sqrt[a];

expr = {Sqrt[x^2], Sqrt[x^2 * y], Sqrt[x^2*y^2], Sqrt[x^2*y*z],
Sqrt[x^4*y^2 *z]};

Using ReplaceAll (/.)

expr /. rule

{x, x Sqrt[y], x Sqrt[y^2], x Sqrt[y z], x^2 Sqrt[y^2 z]}

However, in general ReplaceRepeated (//.) is needed

expr //. rule

(* {x, x Sqrt[y], x y, x Sqrt[y z], x^2 y Sqrt[z]} *)
• Perfect, that's exactly what I wanted!
– TeM
Feb 17 '20 at 14:04

Why not use PowerExpand:

PowerExpand[Sqrt[x^2 y]]

x Sqrt[y]