Versions Compared

Key

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

...

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 rule NUM08-J. Check floating-point inputs for exceptional values for additional information).

...

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 value.:

Code Block
bgColor#ccccff
public class NaNComparison {
  public static void main(String[] args) {
    double x = 0.0;	  
    double result = Math.cos(1/x); // Returns NaN when input is infinity
    if (Double.isNaN(result)) { 
      System.out.println("result is NaN");
    }
  }
}

...

...