Java isNan how it works?

后端 未结 5 1975
别那么骄傲
别那么骄傲 2021-02-04 03:04

I was looking at the openjdk-1.7.0_25 source code and I have seen this method:

/**
 * Returns {@code true} if the specified number is a
 * Not-a-Num         


        
5条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 03:22

    That method can return true for certain operations, for example:

    System.out.println(Float.isNaN(0.0f / 0.0f));
    System.out.println(Double.isNaN(Math.sqrt(-1)));
    

    Basically, NaN represents an undefined value. The value of 0.0 / 0.0 is NaN, and Nan != NaN. It may seem logical because Math.sqrt(-1) also gives you NaN.

    See the javadoc of Double.NaN:

    It is equivalent to the value returned by Double.longBitsToDouble(0x7ff8000000000000L)

    And then Double.longBitsToDouble():

    If the argument is any value in the range 0x7ff0000000000001L through 0x7fffffffffffffffL or in the range 0xfff0000000000001L through 0xffffffffffffffffL, the result is a NaN. No IEEE 754 floating-point operation provided by Java can distinguish between two NaN values of the same type with different bit patterns.

提交回复
热议问题