为什么Number.MAX_SAFE_INTEGER 9,007,199,254,740,991而不是9,007,199,254,740,992? [英] Why is Number.MAX_SAFE_INTEGER 9,007,199,254,740,991 and not 9,007,199,254,740,992?
问题描述
ECMAScript 6的 Number.MAX_SAFE_INTEGER
应该表示JavaScript在浮点精度出现问题之前可以存储的最大数值。但是,要求添加到此值的数字1也必须表示为数字
。
ECMAScript 6's Number.MAX_SAFE_INTEGER
supposedly represents the maximum numerical value JavaScript can store before issues arise with floating point precision. However it's a requirement that the number 1 added to this value must also be representable as a Number
.
Number.MAX_SAFE_INTEGER
注意
Number的值.MAX_SAFE_INTEGER
是最大的整数n
,这样n
和n + 1
都可以完全表示为Number
值。
Number.MAX_SAFE_INTEGER
NOTE The value of
Number.MAX_SAFE_INTEGER
is the largest integern
such thatn
andn + 1
are both exactly representable as aNumber
value.
Number.MAX_SAFE_INTEGER
的值为 9007199254740991(2 ^ 53-1)
。
Chrome,Firefox,Opera和IE11的JavaScript控制台都可以安全地执行9,007,199,254,740,992的计算。一些测试:
The JavaScript consoles of Chrome, Firefox, Opera and IE11 can all safely perform calculations with the number 9,007,199,254,740,992. Some tests:
// Valid
Math.pow(2, 53) // 9007199254740992
9007199254740991 + 1 // 9007199254740992
9007199254740992 - 1 // 9007199254740991
9007199254740992 / 2 // 4503599627370496
4503599627370496 * 2 // 9007199254740992
parseInt('20000000000000', 16) // 9007199254740992
parseInt('80000000000', 32) // 9007199254740992
9007199254740992 - 9007199254740992 // 0
9007199254740992 == 9007199254740991 // false
9007199254740992 == 9007199254740992 // true
// Erroneous
9007199254740992 + 1 // 9007199254740992
9007199254740993 + "" // "9007199254740992"
9007199254740992 == 9007199254740993 // true
为什么要求 n + 1
必须也可以表示为数字
?为什么失败会使值不安全?
Why is it a requirement that n + 1
must also be representable as a Number
? Why does failing this make the value unsafe?
推荐答案
我会说它因为 Math.pow(2,53)
是最大的可直接表示的整数,它的不安全,因为它也是表示的第一个值也是另一个值的近似值:
I would say its because while Math.pow(2, 53)
is the largest directly representable integer, its unsafe in that its also the first value who's representation is also an approximation of another value:
9007199254740992 == 9007199254740993 // true
与相比,Math.pow(2,53) - 1
9007199254740991 == 9007199254740993 // false
这篇关于为什么Number.MAX_SAFE_INTEGER 9,007,199,254,740,991而不是9,007,199,254,740,992?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!