考虑这段代码( 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 可以处理的最大整数值是多少?
我正在实现最大为 2^64 的随机整数生成器。有什么我应该注意的陷阱吗?
最佳答案
How javascript treat large integers?
JS 没有整数。 JS 数字是 64 位 float 。它们存储为尾数和指数。
精度由尾数给出,大小由指数给出。
如果您的数字需要比尾数中存储的更精确,最低有效位将被 chop 。
9007199254740992; // 9007199254740992
(9007199254740992).toString(2);
// "100000000000000000000000000000000000000000000000000000"
// \ \ ... /\
// 1 10 53 54
// The 54-th is not stored, but is not a problem because it's 0
9007199254740993; // 9007199254740992
(9007199254740993).toString(2);
// "100000000000000000000000000000000000000000000000000000"
// \ \ ... /\
// 1 10 53 54
// The 54-th bit should be 1, but the mantissa only has 53 bits!
9007199254740994; // 9007199254740994
(9007199254740994).toString(2);
// "100000000000000000000000000000000000000000000000000010"
// \ \ ... /\
// 1 10 53 54
// The 54-th is not stored, but is not a problem because it's 0
然后,您可以存储所有这些整数:
-9007199254740992, -9007199254740991, ..., 9007199254740991, 9007199254740992
第二个称为 minimum safe integer :
The value of
Number.MIN_SAFE_INTEGER
is the smallest integer n such that n and n − 1 are both exactly representable as a Number value.The value of
Number.MIN_SAFE_INTEGER
is −9007199254740991 (−(253−1)).
倒数第二个叫做 maximum safe integer :
The value of
Number.MAX_SAFE_INTEGER
is the largest integer n such that n and n + 1 are both exactly representable as a Number value.The value of
Number.MAX_SAFE_INTEGER
is 9007199254740991 (253−1).
关于javascript - javascript 如何处理大整数(超过 52 位)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52356673/