Versions Compared

Key

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

Wiki Markup
According to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\], Section 4.2.3, "Floating-Point Types, Formats, and Values|http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3]\]:":

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.

...

A frequently encountered mistake is the doomed comparison with NaN, typically in expressions. As per its semantics, no value (including NaN itself) can be compared to NaN using common operators. This noncompliant code example demonstrates one of the many violations.

Code Block
bgColor#FFcccc
public class NaNComparison {
  public static void main(String[] args) {
    double x = 0.0;
    double result = Math.cos(1/x); // returns NaN if input is infinity
    if(result == Double.NaN) { // compare with infinity
      System.out.println("Both are equal");
    }
  }
}

Compliant Solution

This compliant solution uses the method Double.isNaN() to check if 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 if input is infinity
    if(Double.isNaN(result)) { 
      System.out.println("Both are equal");
    }
  }
}

Risk Assessment

Comparisons with NaN values may lead to unexpected results.

...