Why do comparisons of NaN values behave differently from all other values? That is, all comparisons with the operators ==, <=, >=, <, > where one or both values is NaN
To throw in yet another analogy. If I hand you two boxes, and tell you that neither of them contains an apple, would you tell me that the boxes contain the same thing?
NaN contains no information about what something is, just what it isn't. Therefore these elements can never definitely be said to be equal.
I don't know the design rationale, but here's an excerpt from the IEEE 754-1985 standard:
"It shall be possible to compare floating-point numbers in all supported formats, even if the operands' formats differ. Comparisons are exact and never overflow nor underflow. Four mutually exclusive relations are possible: less than, equal, greater than, and unordered. The last case arises when at least one operand is NaN. Every NaN shall compare unordered with everything, including itself."
From the wikipedia article on NaN, the following practices may cause NaNs:
Since there is no way to know which of these operations created the NaN, there is no way to compare them that makes sense.
Very short answer:
Because the following:
nan / nan = 1
must NOT hold. Otherwise inf/inf
would be 1.
(Therefore nan
can not be equal to nan
. As for >
or <
, if nan
would respect any order relation in a set satisfying the Archimedean property, we would have again nan / nan = 1
at the limit).
I'm guessing that NaN (Not A Number) means exactly that: This is not a number and thus comparing it does not really make sense.
It's a bit like arithmetic in SQL with null
operands: They all result in null
.
The comparisons for floating point numbers compare numeric values. Thus, they can't be used for non numeric values. NaN therefore cannot be compared in a numeric sense.
The over-simplified answer is that a NaN has no numeric value, so there is nothing in it to compare to anything else.
You might consider testing for and replacing your NaNs with +INF if you want them to act like +INF.