Versions Compared

Key

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

According to the The Java Language Specification (JLS), §4§4.2.3, "Floating-Point Types, Formats, and Values" [JLS 2005]:

...

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

Noncompliant Code Example

...

Code Block
bgColor#FFcccc
public class NaNComparison {
  public static void main(String[] args) {
    double x = 0.0;
    double result = Math.cos(1/x); // returnsReturns NaN if input is infinity
    if (result == Double.NaN) { // comparisonComparison is always false!
      System.out.println("result is NaN");
    }
  }
}

...

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

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

NUM07-J

lowLow

probableProbable

mediumMedium

P4

L3

Automated Detection

Automated detection of comparison with NaN 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.

Bibliography

 

...