Why am I seeing what looks like a violation of operator precedence?


Why is it that when I evaluate


I get

(* -2.93688 *)

which is wrong.

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

Any help would be appreciated.

An old man in the sea.

Posted 2017-08-07T14:56:57.423

Reputation: 2 335

What result were you expecting? – J. M.'s ennui – 2017-08-07T14:59:48.660

@J.M. I've edited the question. Thanks – An old man in the sea. – 2017-08-07T15:02:21.143

2FullForm[Hold[2*2.848529281693615`+3*-0.5155083247776808`]] should reveal how Mathematica is interpreting your expression. Moral lesson: use parentheses when in doubt. – J. M.'s ennui – 2017-08-07T15:06:02.713

@J.M. thanks ;) – An old man in the sea. – 2017-08-07T15:11:10.780



Consider the following:



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



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

C. E.

Posted 2017-08-07T14:56:57.423

Reputation: 67 448

Thanks for the answer – An old man in the sea. – 2017-08-07T17:24:18.813

You're very welcome :) – C. E. – 2017-08-07T17:34:46.927


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 +.

David Jacobson

Posted 2017-08-07T14:56:57.423

Reputation: 41