According to \[[JLS 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]\]: |
NaN is unordered, so the numerical comparison operators
<,<=,>, and>=returnfalseif either or both operands areNaN. The equality operator==returnsfalseif either operand isNaN, and the inequality operator!=returnstrueif either operand isNaN.
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 a NaN value as input.
A frequently encountered mistake is the doomed comparison with NaN, typically in expressions. As per its semantics, no value (including NaN itself) can be compared to NaN using common operators. This noncompliant example demonstrates one of the many violations.
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("Both are equal");
}
}
|
This compliant solution uses Double.isNaN to check if the expression corresponds to a NaN value.
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("Both are equal");
}
}
|
Comparisons with NaN values may lead to unexpected results.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
FLP02- J |
low |
probable |
medium |
P4 |
L3 |
TODO
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[JLS 05|AA. Java References#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 08|AA. Java References#FindBugs 08]\] FE: Doomed test for equality to NaN |
FLP01-J. Take care in rearranging floating point expressions 06. Floating Point (FLP) FLP30-J. Do not use floating point variables as loop counters