javascript如何处理大整数(超过52位)? [英] How javascript treat large integers (more than 52 bits)?

查看:102
本文介绍了javascript如何处理大整数(超过52位)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这段代码(node v5.0.0)

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

为什么 a === b 是真的吗?

javascript可以处理的最大整数值是多少?

What is the maximum integer value javascript can handle?

我正在实现最多2 ^ 64的随机整数生成器。我应该注意哪些缺陷?

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

推荐答案

。:: JavaScript仅支持53位整数::。



JavaScript中的所有数字都是浮点数,这意味着整数总是表示为

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

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

sign × mantissa × 2exponent

尾数有53位。你可以使用指数来获得更高的整数,但是它们将不再是连续的。例如,您通常需要将尾数乘以2(指数1)以达到第54位。

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.

但是,如果乘以2,则只能表示每二个整数:

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

加法期间的舍入效应会使奇数增量无法预测(+1对+3)。实际表示有点复杂,但这个解释应该可以帮助您理解基本问题。

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.

您可以安全地使用 strint 库对字符串中的大整数进行编码,并对它们执行算术运算。

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

这里是完整的文章。

这篇关于javascript如何处理大整数(超过52位)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆