I would like Mathematica to Simplify all further expressions with Abs[#]^2&
to #^2&
is there a way i can do that?
1 Answer
This can be done quite simply, but note the warnings below.
(* This works, but it is a bad idea: *)
Unprotect[Abs];
Abs /: Abs[x_]^k_ /; TrueQ[k == 2] := x^2;
Protect[Abs];
Abs[x]^2
x^2
Warnings
Although this looks nice if you're used to working with real numbers, it's a bad idea. Here are a few examples of why:
Abs[x*I + 3]^2
(x*I + 3)^2 (* This is clearly wrong *)
{Abs[x*I + 3]^2 /. x -> 2, (Abs[x*I + 3] /. x -> 2)^2}
{5 + 12*I, 13} (* These should be the same *)
Additionally, it is very difficult to intuit where and how the Mathematica internals use rules like this to simplify things during calls to functions like D
, Simplify
, Solve
, etc. It's likely that a call to Integrate
will fail or be wrong after this rule is added because of some interaction happening in the Mathematica guts. In short: do this only if you know why and what you're doing; if you don't feel that there is an alternative, at least do it for a limited scope by using the Block
form:
Block[
{Abs},
Abs /: Abs[x_]^k_ /; TrueQ[k == 2] := x^2;
(* code here obeys the above rule *)
Abs[x]^2]
x^2
(* Code outside the Block uses the original Abs *)
Abs[x]^2
Abs[x]^2
Better
A far better idea is to go with Bob Hanlon's comment/suggestions to correctly state your $Assumptions
and use Simplify
and Refine
.
Block[
{$Assumptions = Element[x, Reals]},
Simplify[Abs[x]^2]]
x^2
Abs[#]^2&=#^2&
$\endgroup$$Pre
values ($Pre
,$PreRead
,$PrePrint
) e.g.$Pre=(# /. Abs[x_]^2 :> x^2) &
. This applies your rule to every input expression. I admit I don't have much experience with these, so I can't comment on unintended consequences. $\endgroup$Abs[x]^2 == x^2
is only valid for realx
. Since Mathematica generally operates in the complex plane, you are likely to generate problems. Specify real variables in$Assumptions
and any function that accepts assumptions (e.g.,Simplify
) will make the simplification that you want for real values. $\endgroup$