user1518183 - 8 months ago 48

Node.js Question

Consider this code (node v5.0.0)

`const a = Math.pow(2, 53)`

const b = Math.pow(2, 53) + 1

const c = Math.pow(2, 53) + 2

console.log(a === b) // true

console.log(a === c) // false

Why

`a === b`

What is the maximum integer value javascript can handle?

I'm implementing random integer generator up to 2^64. Is there any pitfall I should be aware of?

Answer

All numbers in JavaScript are floating point which means that integers are always represented as

```
sign × mantissa × 2exponent
```

The mantissa has 53 bits. You can use the exponent to get higher integers, but then they won’t be contiguous, any more. For example, you generally need to multiply the mantissa by two (exponent 1) in order to reach the 54th bit.

However, if you multiply by two, you will only be able to represent every second integer:

```
Math.pow(2, 53) // 54 bits 9007199254740992
Math.pow(2, 53) + 1 // 9007199254740992
Math.pow(2, 53) + 2 //9007199254740994
Math.pow(2, 53) + 3 //9007199254740996
Math.pow(2, 53) + 4 //9007199254740996
```

Rounding effects during the addition make things unpredictable for odd increments (+1 versus +3). The actual representation is a bit more complicated but this explanation should help you understand the basic problem.

You can safely use strint library to encode large integers in strings and perform arithmetic operations on them too.

Here is the full article.