[ACCEPTED]-Float.NaN == Float.NaN-nan

Accepted answer
Score: 68

Use Float.isNaN to check for NaN values.


Score: 38

Because Java implements the IEEE-754 floating 7 point standard which guarantees that any 6 comparison against NaN will return false (except 5 != which returns true)

That means, you can't 4 check in your usual ways whether a floating 3 point number is NaN, so you could either 2 reinterpret both numbers as ints and compare 1 them or use the much cleverer solution:

def isNan(val):
     return val != val
Score: 0

All I need to say is: Wikipedia About NaN.

It is written quite 36 clearly. The interesting part is that the 35 floating point NaN of the common standard 34 expresses a NaN this way:

s111 1111 1xxx 33 xxxx xxxx xxxx xxxx xxxx

The s is the sign 32 (negative or positive), the 1's are the 31 exponent and the x is regarded as a payload.

Looking 30 at the payload a NaN is not equal any NaN 29 and there are rare chances that these information 28 of the payload are interesting for you as 27 a developer (e.g. complex numbers).

Another 26 thing is that in the standard they have 25 signalling and quite NaN. A signalling NaN 24 (sNaN) means an NaN that should raises a 23 reaction like a exception. It should be 22 used to say out loud that you have a problem 21 in your equation. A quiet NaN (qNaN) is 20 a NaN that is silently passed on.

A sNaN 19 that created a signal is converted to a 18 qNaN to not further produce any more signals 17 in subsequent operations. Remember some 16 system define i^0 = 1 as a constant that 15 NaN^0 = 1 holds true. So there are cases 14 where people calculate with NaN.

So in the 13 end I would go with this: qNaN != sNaN but 12 this is internal and is not observable for 11 the user (you cant check that). Mix along 10 the payment and the sign (yes you can have 9 negative and positive NaN) and it appears 8 to me that always return NaN != NaN looks 7 like a much wiser choice that I finally 6 learned to appreciate -> I will never 5 ever complain or wonder about the inequality 4 of NaN again. Praise the folks who were 3 that thoughtful giving us such a good standard!

By 2 the way: Java uses a positive NaN with a 1 payload of 0 (all x are zeros).

More Related questions