9
$\begingroup$

Why is it that when I evaluate

2*2.848529281693615`+3*-0.5155083247776808`

I get

(* -2.93688 *)

which is wrong.

2*2.848529281693615` + (3*-0.5155083247776808`)
(* 4.15053 *)

Any help would be appreciated.

$\endgroup$
  • $\begingroup$ What result were you expecting? $\endgroup$ – J. M. is in limbo Aug 7 '17 at 14:59
  • $\begingroup$ @J.M. I've edited the question. Thanks $\endgroup$ – An old man in the sea. Aug 7 '17 at 15:02
  • 2
    $\begingroup$ FullForm[Hold[2*2.848529281693615`+3*-0.5155083247776808`]] should reveal how Mathematica is interpreting your expression. Moral lesson: use parentheses when in doubt. $\endgroup$ – J. M. is in limbo Aug 7 '17 at 15:06
  • $\begingroup$ @J.M. thanks ;) $\endgroup$ – An old man in the sea. Aug 7 '17 at 15:11
9
$\begingroup$

Consider the following:

2.84852`+3

2.85

This syntax means "write 2.84852 with 3 digits of precision". You're saying that this is equivalent to

2.84852+3

5.84852

Which it is not. Documentation: http://reference.wolfram.com/language/tutorial/NumericalPrecision.html

$\endgroup$
  • $\begingroup$ Thanks for the answer $\endgroup$ – An old man in the sea. Aug 7 '17 at 17:24
  • $\begingroup$ You're very welcome :) $\endgroup$ – C. E. Aug 7 '17 at 17:34
4
$\begingroup$

The problem has to do with the representation of approximate real numbers, but it is also a quasi-bug in the documentation.

To get the real info, go to tutorial/InputSyntax. You will see a form number`s, which is used to indicate that the number has a precision of s decimal digits. And you read down to the 4th paragraph under Numbers, there is this sentence:

The precision or accuracy s can be any real number; it does not need to be an integer.

Nothing in the section on Numbers mentions + or - or representing negative numbers. But apparently -3 is a real number, not the unary minus operator applied to 3. And +3 is also a real number. (This is the bug in the documentation.)

So 2.848529281693615`+3 is 2.848529281693615 with a precision of 3 decimal digits. (Elsewhere the documentation says that small precision numbers are (sort of) fluffed up to machine precision, yet some attribute is put on it so that it prints to just the declared precision. But if you do any arithmetic on it or view it with FullForm, you can see that all the original digits are really preserved.)

So, the whole expression is parsed as

2*2.848529281693615 * -0.5155083247776808`

And that's why you get -2.93688.

You can get the correct answer by just inserting a space between 2.848529281693615` and +.

$\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.