Versions Compared

Key

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

...

Noncompliant Code Example

A frequently encountered mistake is the doomed This noncompliant code example attempts a direct comparison with NaN, typically in expressions. As per its the semantics , no value (including NaN itself) can be compared to NaN using common operators. This noncompliant code example demonstrates one of the many violationsof 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 equal" 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) { // comparecomparison is withalways infinityfalse!
      System.out.println("Both are equal");
    }
  }
}

...

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

...

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

FLP05-J

low

probable

medium

P4

L3

Automated Detection

TODOAutomated detection of floating point comparison operators 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 may be useful.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

Bibliography

Wiki Markup
\[[FindBugs 2008|AA. Bibliography#FindBugs 08]\] FE: Doomed test for equality to NaN
\[[JLS 2005|AA. Bibliography#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]
\[[FindBugs 2008|AA. Bibliography#FindBugs 08]\] FE: Doomed test for equality to NaN

...

FLP04-J. Use the strictfp modifier for floating point calculation consistency      07. Floating Point (FLP)      FLP06-J. Check floating point inputs for exceptional values