JavaScript中的最大整数值 [英] max integer value in JavaScript
问题描述
我正在阅读 Eloquent JavaScript一书的第二章。作者声明:
I'm reading the second chapter of the book Eloquent JavaScript. The author states that:
任何小于2 ^ 52的整数(超过10 ^ 15)将安全地放入一个JavaScript编号。
我从维基百科。
4,503,599,627,370,496
该值必须小于2 ^ 52,所以我减去了1初始值;
The value has to be less than 2^52, so I've substracted 1 from the initial value;
var max = 4503599627370495;
定义max变量后,我正在检查值是多少(我正在使用 Chrome 32.0.1700.77
)。
After defining the max variable I'm checking what's the value (I'm using Chrome 32.0.1700.77
).
console.log(max); // 4503599627370495
我想看看当我超过这个限制时会发生什么,所以我' m加几次。
I'd like to see what happens when I go over this limit, so I'm adding one a couple of times.
出乎意料:
max += 1;
console.log(max); // 4503599627370496
max += 1;
console.log(max); // 4503599627370497
max += 1;
console.log(max); // 4503599627370498
我超过限制,计算仍然精确。
I went over the limit and the calculations are still precise.
我尝试了下一个2的幂,2 ^ 53,这次我没有减去1:
I tried the next power of two instead, 2^53, I didn't substract 1 this time:
9,007,199,254,740,992
var max = 9007199254740992;
这个似乎是一个更大的限制,似乎我可以非常安全地添加和减去数字:
This one seems to be a bigger limit, it seems that I can quite safely add and substract numbers:
max += 1;
console.log(max); // 9007199254740992
max += 1;
console.log(max); // 9007199254740992
max -= 1;
console.log(max); // 9007199254740991
max += 1;
console.log(max); // 9007199254740992
max -= 900;
console.log(max); // 9007199254740092
max += 900;
console.log(max); // 9007199254740992
我可以为最大值分配更大的值,但是它会失去精度而且我可以不能再安全地添加或减去数字。
I can assign even a bigger value to the max, however it loses precision and I can't safely add or substract numbers again.
您能否准确解释引擎盖下的机制?高于2 ^ 52之后比特会发生什么事情的一个例子真的很有帮助。
推荐答案
这是不是强类型编程语言。 JS有一个对象 Number
。你甚至可以得到一个无穷大的数字: document.write(Math.exp(1000));
。
This is not a strongly typed programming language. JS has an object Number
. You can even get an infinite number: document.write(Math.exp(1000));
.
document.write(Number.MIN_VALUE + "<br>");
document.write(Number.MAX_VALUE + "<br>");
document.write(Number.POSITIVE_INFINITY + "<br>");
document.write(Number.NEGATIVE_INFINITY + "<br>");
alert([
Number.MAX_VALUE/(1e293),
Number.MAX_VALUE/(1e292),
Number.MAX_VALUE/(1e291),
Number.MAX_VALUE/(1e290),
].join('\n'))
希望这是一个有用的答案。谢谢!
Hope it's a useful answer. Thanks!
更新:
max int is - +/- 9007199254740992
UPDATE: max int is - +/- 9007199254740992
这篇关于JavaScript中的最大整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!