Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange JavaScript Number behavior

I found the following weird behavior while working on JavaScript numbers.

var baseNum = Math.pow(2, 53);
console.log(baseNum); //prints 9007199254740992

console.log(baseNum + 1); //prints 9007199254740992 again!

console.log(baseNum + 2); //prints 9007199254740994, 2 more than +1

console.log(baseNum + 3) // prints 9007199254740996, 2 more than +2
console.log(baseNum + 4) // prints 9007199254740996, same as +3

What is happening here? I understand that JavaScript can only represent numbers upto 2^53 (they are internally 'double'?), but why this behavior?

If 2^53 is the practical max, then why do we have Number.MAX_VALUE (1.7976931348623157e+308)?.

like image 834
Ashwin Prabhu Avatar asked Sep 26 '12 05:09

Ashwin Prabhu


1 Answers

The number is really a double. The mantissa has 52-bits (source and extra information on doubles). Therefore, storing 2^53 chops off the one bit.

The number is stored using 3 pieces a sign bit (fairly straight forward) and two other pieces, the mantissa M and the exponent E. The number is calculated as:

(1 + M/2^53) * 2^(E-1023)

I might have some of the specifics there a little off, but the basic idea is there. So when the number is 2^53, 2^(E-1023) = 2^53 and since there are only 52 bits in M, you can no longer represent the lowest bit.

like image 128
CrazyCasta Avatar answered Oct 16 '22 05:10

CrazyCasta