Java是不是它的工作原理?

ras*_*cio 17 java floating-point nan

我在看openjdk-1.7.0_25源代码,我看过这个方法:

/**
 * Returns {@code true} if the specified number is a
 * Not-a-Number (NaN) value, {@code false} otherwise.
 *
 * @param   v   the value to be tested.
 * @return  {@code true} if the argument is NaN;
 *          {@code false} otherwise.
 */
static public boolean isNaN(float v) {
    return (v != v);
}
Run Code Online (Sandbox Code Playgroud)

当这种方法可以返回时,我无法理解它是如何工作的true

Roh*_*ain 21

对于某些操作,该方法可以返回true,例如:

System.out.println(Float.isNaN(0.0f / 0.0f));
System.out.println(Double.isNaN(Math.sqrt(-1)));
Run Code Online (Sandbox Code Playgroud)

基本上,NaN代表一个未定义的值.的价值0.0 / 0.0NaN,和Nan != NaN.它似乎合乎逻辑,因为它Math.sqrt(-1)也给你NaN.

查看javadoc Double.NaN:

它相当于返回的值 Double.longBitsToDouble(0x7ff8000000000000L)

然后Double.longBitsToDouble():

如果参数是在范围内的任何值0x7ff0000000000001L通过0x7fffffffffffffffL或在范围0xfff0000000000001L通过0xffffffffffffffffL,其结果是一个NaN.Java提供的IEEE 754浮点运算不能区分具有不同位模式的相同类型的两个NaN值.