7
$\begingroup$

When I enter f + 0 where f is an undefined symbol, I get f. So far so good. When I enter f + 0., I get f + 0.. How can I get Mathematica to simplify 0. just like it does for 0? I tried using Simplify, I got the same result.

$\endgroup$
  • 1
    $\begingroup$ Because f+0. is not same as f. Compare Pi+0 and Pi+0. The latter is a machine precision number. Run #[Pi + 0, Pi + 0.] & /@ {SameQ, Equal} to see the difference. $\endgroup$ – BlacKow Sep 1 '16 at 19:37
14
$\begingroup$

Another reason why 0. is not removed is that it is an inexact zero. In other words, it represents something that is zero to a certain precision, but unknown beyond that.

The usual way to convert very small inexact numbers to an exact zero is Chop. An exact zero will be removed immediately.

Chop[f + 0.]
(* f *)

I do not recommend using a replacement rule to remove it. Why? It's because replacement rules use patterns, which will match only on structurally identical expressions (not mathematically equal ones). There are several structurally different expressions which look like zero and are effectively zero. Yet a simple pattern will only match one of them. Try e.g. f + 0.``20, or a "no precision left" zero arising from catastrophic cancellation.

$\endgroup$
6
$\begingroup$

As @BlacKow pointed out Pi+0. differs from Pi so Mathematica is right not to remove the +0.. One option is to use a replacement rule

f+0. /. {x_+0.:>x}
$\endgroup$
  • 2
    $\begingroup$ You can also do f + 0. /. 0. -> 0, or f + 0. // Chop. $\endgroup$ – kirma Sep 1 '16 at 19:43
6
$\begingroup$

From the doc :

  • Chop[expr,delta] replaces numbers smaller in absolute magnitude than delta by 0.

  • Chop uses a default tolerance of 10^-10.

Accordingy :

Chop[f + 1. 10^-20]

gives :

f

You might want very small values not to canceled. In that case you can use the two arguments syntax of Chop:

Chop[f + 1. 10^-20, 10^-30]

1.*10^-20 + f

But if you have no idea of the magnitude of what is negligible or not, it seems that you can use Rationalize[..., 0] :

Rationalize[f + 0., 0]   

f

Rationalize[f + 1. 10^-20, 0]  

1/100000000000000005484 + f

and then return to classic machine-precision number :

N[Rationalize[f + 1. 10^-20, 0]]

1.*10^-20 + f

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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