Versions Compared

Key

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

...

Because this unordered property is often unexpected, 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 rule "NUM11-J. Check floating-point inputs for exceptional values" for additional information.

Noncompliant Code Example

This noncompliant code example attempts a direct comparison with NaN. In accordance with the semantics of NaN, all comparisons with NaN yield false (with the exception of the != operator, which returns true). Consequently, this comparison always return false, and the "result 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("result is NaN");
    }
  }
}

Compliant Solution

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

Risk Assessment

Comparisons with NaN values can lead to unexpected results.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

NUM10-J

low

probable

medium

P4

L3

Automated Detection

Automated 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 could be useful.

FindBugs checks for the specific case of comparison with a constant NaN.

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="20aca3728ad31b4a-61c14439-44a64ca7-b4158d1e-2c5ebe985cea5af98e29655b"><ac:plain-text-body><![CDATA[

[[FindBugs 2008

AA. Bibliography#FindBugs 08]]

FE: Doomed test for equality to NaN

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="e77b4b1b1025ee1c-1461a252-44e64de3-b1cda7ae-7e0ec6b8ed14217b303d6e1a"><ac:plain-text-body><![CDATA[

[[JLS 2005

AA. Bibliography#JLS 05]]

[§4.2.3, "Floating-Point Types, Formats, and Values"

http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3]

]]></ac:plain-text-body></ac:structured-macro>

...