According to The Java Language Specification (JLS), §4.2.3, "Floating-Point Types, Formats, and Values" [JLS 20052015]:
NaN(not-a-number) is unordered, so the numerical comparison operators<,<=,>, and>=returnfalseif either or both operands areNaN. The equality operator==returnsfalseif either operand isNaN, and the inequality operator!=returnstrueif either operand isNaN.
...
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.
...
Comparisons with NaN values can lead to unexpected results.
Rule | Severity | Likelihood | Detectable |
|---|
Repairable | Priority | Level | |
|---|---|---|---|
NUM07-J | Low | Probable | Yes |
Yes |
P6 |
L2 |
Automated Detection
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.
| Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| Klocwork |
| JAVA.COMPARE.NAN | |||||||
| Parasoft Jtest |
| CERT.NUM07.NAN | Avoid comparisons to Double.NaN or Float.NaN | ||||||
| PVS-Studio |
| V6038 |
Bibliography
...
...