Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java isNan how it works?

Tags:

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-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); } 

I can't understand how it works, when this method can return true?

like image 903
rascio Avatar asked Aug 26 '13 10:08

rascio


People also ask

How does Java handle NaN value?

Java Double isNaN() Method The isNaN() method of Java Double class returns true: If the value of this Object is Not-a-Number (NaN). If the argument passed is Not-a-Number (NaN). Otherwise, the method returns false.

Does isNaN work for floats?

The Float. isNaN() method in Float Class is a built in method in Java returns true if this Float value or the specified float value is Not-a-Number (NaN), or false otherwise.

What is double NaN?

public static final double NaN. A constant holding a Not-a-Number (NaN) value of type double . It is equivalent to the value returned by Double.

Is there NaN in Java?

“NaN” as many of you have guessed, is used to represent “Not a Number” in Java. It is a special floating point value to denote overflows and errors. It is generated when a floating point number is divided by zero or if the square root of a negative number is computed. For example, have a look at the following snippet.


1 Answers

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.

like image 112
Rohit Jain Avatar answered Sep 21 '22 07:09

Rohit Jain