1

I'm having trouble summing 3 double numbers in MATLAB Command Window, here are my variables

>> a = 0.45;
>> b = 0.05;
>> c = -0.5;

when I sum them like this, I get 1.3878e-17

>> c + a + b
ans =
   1.3878e-17

But when I use parentheses, it returns 0

>> c + (a + b)
ans =
 0

Also summing them in this order returns 0 again

>> a + b + c
ans =
 0
Brison
  • 58
  • 5
  • 2
    Look at hidden round off errors - https://au.mathworks.com/help/symbolic/digits.html . This simply appears to be caused by the precision of implicit cast. – Aamir Mulla Jul 22 '17 at 06:02

1 Answers1

1

In usual storage of floats in programming languages using IEEE 754. Therefore, for storage of some floating numbers which cannot be shown by sum of some 2^i, there wouldbe some errors (in base 2) such as 0.3.

As mentioned in comments, you can use digits to find these errors:

digits(100);
vpa(a)
     >> 0.4500000000000000111022302462515654042363166809082031250000000000000000000000000000000000000000000000 
vpa(b)
     >> 0.05000000000000000277555756156289135105907917022705078125000000000000000000000000000000000000000000000
vpa(c)
     >> -0.5000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
vpa(a+b)
     >> 0.5000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000    

vpa(c+a)
     >> -0.04999999999999998889776975374843459576368331909179687500000000000000000000000000000000000000000000000

As you can see in the above, because of this error, sum of a and c is not as exactly as you've expected (because of error in storage of floating points in base 2 in IEEE 754).

Therefore, there order of + is important as you found through these expressions. Hence, the preference of plus is from left to right, and preference of parenthesis is higher than plus, in the c + (a + b) and a + b + c, the a + b is done first,. Then, you can see the sum is exact in the above. However, in c + a + b, the c + a is happened sooner and you can see this sum is not exact, so the result of this sum with b could have some error.

In this way, you can find a + c + b is not exact as you want. And:

vpa(c + b)
    >> -0.4500000000000000111022302462515654042363166809082031250000000000000000000000000000000000000000000000

So,

c + b + a
    >> 0
OmG
  • 18,337
  • 10
  • 57
  • 90