gpt4 book ai didi

javascript - 添加到 Number.MAX_VALUE

转载 作者:行者123 更新时间:2023-11-28 05:27:06 25 4
gpt4 key购买 nike

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

如果你有这样的代码

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

然后我希望向 Number.MAX_VALUE 添加任何东西都会将其推至无穷大。结果只是 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“将加法运算符应用于数字”):

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“舍入方向属性到最近”)

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以便四舍五入到无穷大。否则,它会四舍五入到 MAX_VALUE,因为它比无穷大更接近。

请注意,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/40059348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com