5

Note : I'm not asking why is 0.1 + 0.2 different from 0.3.

According to Is floating point math broken?, 0.1+0.2 does not equal to 0.3, because 0.1 and 0.2 are already rounded to different numbers before comparing, which is different from rounded number from 0.3.

But my question is, why 0.1+0.2+0.3!=0.3+0.2+0.1?

console.log(0.1+0.2+0.3==0.3+0.2+0.1);

My assumption: inside computers, floating numbers would be rounded to a value :

0.1 is round to A

0.2 is round to B

0.3 is round to C

since rounded value is exact (can be represented by binary), so I think

A+B+C should be exactly equals to C+B+A, just like 1+2+3 exactly equals to 3+2+1. But now the result is different. What wrong with my assumption?

ocomfd
  • 4,010
  • 2
  • 10
  • 19

2 Answers2

2

Because floating point math is broken.

Addition is performed left-to-right (See #13: Addition).

0.1 + 0.2 + 0.3 equals (0.1 + 0.2) + 0.3 result: 0.3000000000000001 + 0.3
0.3 + 0.2 + 0.1 equals (0.3 + 0.2) + 0.1 result: 0.5 + 0.1

So, yes, this is about 0.1 + 0.2 being different from 0.3

console.log( 0.1 + 0.2  + 0.3);
console.log((0.1 + 0.2) + 0.3);
console.log( 0.3 + 0.2  + 0.1);
console.log((0.3 + 0.2) + 0.1);
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
0

Floating point addition is not associative. Imagine an exaggerated case:

1.0 + (2.053 − 2.053) = 1.0 + 0.0 = 1.0

(1.0 + 2.053) − 2.053 = 2.053 − 2.053 = 0.0

This is because 1.0 + 2.053 is rounded to 2.053, since there are only 53 bits of precision in a 64-bit double precision floating point number, and you need 54 bits to represent 1.0 + 2.053.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
tttapa
  • 1,397
  • 12
  • 26