3
$\begingroup$

I would like Mathematica to Simplify all further expressions with Abs[#]^2& to #^2& is there a way i can do that?

$\endgroup$
9
  • 1
    $\begingroup$ /.Abs[x_]^2:>x^2 $\endgroup$ Nov 29, 2017 at 13:31
  • $\begingroup$ yes but then i need to do this replacement rule in every expression right? I would like somehow that Mathematica does this automatically. I would like something like: Abs[#]^2&=#^2& $\endgroup$
    – Mr Puh
    Nov 29, 2017 at 13:37
  • $\begingroup$ You might try one of the $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$
    – N.J.Evans
    Nov 29, 2017 at 14:05
  • 2
    $\begingroup$ This is highly risky since Abs[x]^2 == x^2 is only valid for real x. 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$
    – Bob Hanlon
    Nov 29, 2017 at 14:14
  • 4
    $\begingroup$ Have you tried to replace Abs by RealAbs? $\endgroup$
    – user64494
    Nov 29, 2017 at 15:36

1 Answer 1

2
$\begingroup$

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.