...
NaN
is unordered, so the numerical comparison operators<
,<=
,>
, and>=
returnfalse
if either or both operands areNaN
. The equality operator==
returnsfalse
if either operand isNaN
, and the inequality operator!=
returnstrue
if either operand isNaN
.
Because this " unordered property " is often unexpected, problems can arise when programmers write code that compares floating point values without considering the semantics of NaN
. For example, input validation checks that fail to consider the possibility of a NaN
value as input may produce unexpected results. See NUM11-J. Check floating point inputs for exceptional values for additional information.
Noncompliant Code Example
This noncompliant code example attempts a direct comparison with NaN
. As per the semantics of NaN
, all comparisons with NaN
yield false (with the exception of the !=
operator, which returns true). Consequently, the this comparison must always alwayss return false, and the "result is NaN" message is never printed.
...
Automated detection of floating point comparison operators is straightforward. Sound determination of whether the possibility of an unordered result has been correctly handled is not feasible in the general case. Heuristic checks could be useful.
Findbugs FindBugs checks for the specific case of comparison with a constant NaN
.
...