javascript - 添加到 Number.MAX_VALUE

标签 javascript math floating-point infinity

这个问题的答案可能非常明显,但我无法在 Mozilla 文档或 Google 上粗略搜索找到它。

如果你有这样的代码

Number.MAX_VALUE + 1; // Infinity, right?
Number.MIN_VALUE - 1; // -Infinity, right?

然后我希望将 任何东西 添加到 Number.MAX_VALUE 会将它推到 Infinity。结果只是 Number.MAX_VALUE 向我吐口水。

但是,当我在 Chrome JS 控制台中玩游戏时,我注意到它实际上并没有变成 Infinity 直到我添加/减去足够多:

Number.MAX_VALUE + Math.pow(100,1000); // now we hit Infinity
Number.MIN_VALUE - Math.pow(100,1000); // -Infinity at last

Number.MAX_VALUEInfinity 之间的这个“缓冲区”的解释是什么?

最佳答案

标准...

在 ECMAScript 中,两个非零有限数的加法实现为(ECMA-262 §11.6.3 "Applying the Additive Operators to Numbers"):

the sum is computed and rounded to the nearest representable value using IEEE 754 round-to-nearest mode. If the magnitude is too large to represent, the operation overflows and the result is then an infinity of appropriate sign.

IEEE-754 的舍入到最近模式指定(IEEE-754 2008 §4.3.1 "Rounding-direction attributes to nearest")

In the following two rounding-direction attributes, an infinitely precise result with magnitude at least bemax ( b − ½ b1-p ) shall round to ∞ with no change in sign; here emax and p are determined by the destination format (see 3.3). With:

  • roundTiesToEven, the floating-point number nearest to the infinitely precise result shall be delivered; if the two nearest floating-point numbers bracketing an unrepresentable infinitely precise result are equally near, the one with an even least significant digit shall be delivered
  • roundTiesToAway, the floating-point number nearest to the infinitely precise result shall be delivered; if the two nearest floating-point numbers bracketing an unrepresentable infinitely precise result are equally near, the one with larger magnitude shall be delivered.

ECMAScript 没有指定哪一个舍入到最近,但在这里并不重要,因为两者给出相同的结果。 ECMAScript中的数字是“double”,其中

  • b = 2
  • emax = 1023
  • p = 53,

因此结果必须至少为 21024 - 2970 ~ 1.7976931348623158 × 10308 in为了四舍五入到无穷大。否则它会四舍五入到 MAX_VALUE,因为 比 Infinity 更接近。

注意 MAX_VALUE = 21024 - 2971,所以你至少需要加上 2971 - 2970 = 2970 ~ 9.979202 × 10291 以获得无穷大。我们可以检查:

>>> Number.MAX_VALUE + 9.979201e291
1.7976931348623157e+308
>>> Number.MAX_VALUE + 9.979202e291
Infinity

与此同时,您的 Math.pow(100,1000) ~ 26643.9 远远超过 21024 - 2970。它已经是无穷大了。

关于javascript - 添加到 Number.MAX_VALUE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10837670/

相关文章:

c# - 生成总和大于提供值的随机但均匀部分的列表

objective-c - const 是在 CGFloat 之前还是之后?

java - 如果 float 不为零,则格式化 float 以显示小数位 java

c - 打印时我的 float 有多余的数字

相当于 Python 的 rsplit 的 JavaScript

javascript - 当没有表单名称时如何清除AngularJS中的表单

javascript - 如何使数组中的第一个变量成为默认变量

asp.net - html 脚本标签不使用类型 javascript <脚本类型 ="text/html">?

math - 如何计算秤的结果?

java - 功率谱自相关