9933272057275866 is this a magic number?

I have a problem and cannot explain it. In fact, I am very surprised. When I try to increase the number 9933272057275866 by 1, it automatically adds 2 !!! See the following code:

let test = 9933272057275866; let test2 = test+1; console.log('Before:', test); console.log('After:', test2); console.log('Sub:', test2-test); 

And the corresponding conclusion:

 Before: 9933272057275866 After: 9933272057275868 Sub: 2 

How is this possible?

Environment is Javascript. I found this problem when I made a call in Hackerrank and then tried to do the same in my own environment on node.js. The same result!

What's happening?

+7
javascript integer-arithmetic
source share
1 answer

Basically, this is because 64 bits (*) are not enough to accurately represent a number.

  • 4341 A521 1037 32ED : 9.93327205727586 6 ⨉ 10 15
  • 4341 A521 1037 32EE : 9.93327205727586 8 ⨉ 10 15

See how it misses the whole between them. In IEEE 754, the higher you go, the more numbers are scattered across the number line. Keep in mind that floating point numbers are approximations. This is why you get this result:

 0.1 + 0.2 === 0.3 // false 

The maximum safe integer in IEEE 754 is 9007199254740991.

More interesting facts with floating point arithmetic:

 A + B == B + A // true, commutative, except when A or B is NaN (A + B) + C == A + (B + C) // false, not associative 

* It is worth noting that numbers in JavaScript (ECMAScript) are represented as 64-bit IEEE 754 doubles. ref

+8
source share

All Articles