Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

NaN is unordered, so the numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN. The equality operator == returns false if either operand is NaN, and the inequality operator != returns true if either operand is NaN.

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.

...