How javascript treat large integers (more than 52 bits)?

后端 未结 5 1514
滥情空心
滥情空心 2020-12-06 22:59

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.         


        
5条回答
  •  执笔经年
    2020-12-06 23:47

    .:: JavaScript only supports 53 bit integers ::.

    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.

提交回复
热议问题