According to The Java Language Specification (JLS), §4.2.3, "Floating-Point Types, Formats, and Values" [JLS 2015]:
NaN(not-a-number) is unordered, so the numerical comparison operators
falseif either or both operands are
NaN. The equality operator
falseif either operand is
NaN, and the inequality operator
trueif either operand is
Because this unordered property is often unexpected, direct comparisons with
NaN must not be performed. 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 can produce unexpected results (see NUM08-J. Check floating-point inputs for exceptional values for additional information).
Noncompliant Code Example
This noncompliant code example attempts a direct comparison with
NaN. In accordance with the semantics of
NaN, all comparisons with
NaN yield false (with the exception of the
!= operator, which returns true). Consequently, this comparison always return
false, and the
"result is NaN" message is never printed.
This compliant solution uses the method
Double.isNaN() to check whether the expression corresponds to a
NaN values can lead to unexpected results.
Automated detection of comparison with
NaN 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.
|PB.NUM.NAN||Avoid comparisons to Double.NaN or Float.NaN|
NUM07-J. Do not attempt comparisons with NaN LiveLesson