Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot

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"":

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.

...

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(&quot;"Both are equal&quot;");
    }
  }
}

Compliant Solution

...

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(&quot;"Both are equal&quot;");
    }
  }
}

Risk Assessment

Comparisons with NaN values may lead to unexpected results.

...

FLP01-J. Take care in rearranging floating point expressions&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      07. Floating Point (FLP)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      FLP03-J. Use the strictfp modifier for floating point calculation consistency