Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript integer overflow

The following code

console.log(Math.pow(2, 53)); 
console.log(Math.pow(2, 53) + 1);

produces exactly same output for both calculations:

9007199254740992

Why?

like image 772
Art Avatar asked Jan 30 '11 00:01

Art


People also ask

What is integer overflow in JavaScript?

In computer programming, an integer overflow occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of digits – either higher than the maximum or lower than the minimum representable value.

Can JavaScript numbers overflow?

Well, in the first case, when JavaScript detects a max overflow, it will just assign Number. MAX_VALUE, while in the second case, when JavaScript detects a min overflow, it just assigns 0.

How do I fix integer overflow?

In languages where integer overflow can occur, you can reduce its likelihood by using larger integer types, like Java's long or C's long long int. If you need to store something even bigger, there are libraries built to handle arbitrarily large numbers.

What happens when integer overflow?

An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).


1 Answers

The result you see occurs because Math.Pow() is working with floating point numbers, and when you reach the 16th decimal digit, you can't necessarily add one to the least significant decimal digit of the value and expect the result to change.

There are typically, in a 64-bit (8-byte) IEEE 754 floating-point binary value, 53 bits for the mantissa (including the implied 1-bit). Your calculation Math.Pow(2, 53) requires 54 bits in the mantissa to be guaranteed of a change. If you add 2, you should see the change.

like image 70
Jonathan Leffler Avatar answered Sep 28 '22 19:09

Jonathan Leffler