为什么-Infinity +Infinity 的平方根在Java?

Why is the square root of -Infinity +Infinity in Java?

我尝试了两种不同的方法来求 Java 的平方根:

Math.sqrt(Double.NEGATIVE_INFINITY); // NaN
Math.pow(Double.NEGATIVE_INFINITY, 0.5); // Infinity

为什么第二种方式 return 不是预期的答案 NaN (与第一种方式相同)?

它就像 Mathdocumentation 中描述的那样。

对于Math.sqrt

If the argument is NaN or less than zero, then the result is NaN.

对于Math.pow

If

  • the first argument is negative zero and the second argument is less than zero but not a finite odd integer, or
  • the first argument is negative infinity and the second argument is greater than zero but not a finite odd integer,

then the result is positive infinity.

至于他们为什么做出这样的设计选择 - 你必须问 java 的作者。

A NaN 返回(根据 IEEE 754)以便在真正未定义的(中间)结果已被计算时继续计算获得。返回 infinity 以便在发生溢出后继续计算。

因此行为

Math.sqrt(Double.NEGATIVE_INFINITY); // NaN

被指定是因为已知(很容易 并且很快 )已经生成了一个未定义的值;完全基于参数的符号。

但是表达式的计算

Math.pow(Double.NEGATIVE_INFINITY, 0.5); // Infinity

同时遇到溢出和无效操作。然而,无效操作识别关键取决于第二个参数的确定有多准确。如果第二个参数是先前舍入操作的结果,那么它可能不是 exactly 0.5。因此,为了避免结果对第二个参数的准确性的严重依赖,返回不太严重的确定,识别溢出。

有关 IEEE 754 标准背后的一些推理的其他详细信息,包括返回标志值而不是生成异常的推理,可在

中找到

What Every Computer Scientist Should Know About Floating-Point Arithmetic (1991, David Goldberg),

这是

的附录D

Sun Microsystems Numerical Computation Guide.