Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor changes to grammar and to string printed in code example

...

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.

Problems Because this "unordered property" is often unexpected, problems can arise when the programmer uses such operators on NaN values in comparison operations. There is also a possibility that the input validation condition does not expect 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.

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 comparison must always return false, and the "Both are equalresult is NaN" message is never printed.

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) { // comparison is always false!
      System.out.println("Bothresult areis equalNaN");
    }
  }
}

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 when input is infinity
    if (Double.isNaN(result)) { 
      System.out.println("Bothresult areis equalNaN");
    }
  }
}

Risk Assessment

Comparisons with NaN values can lead to unexpected results.

...