Wiki Markup |
---|
According to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\], Section 4.2.3, ""Floating-Point Types, Formats, and Values"": |
NaN
is unordered, so the numerical comparison operators<
,<=
,>
, and>=
returnfalse
if either or both operands areNaN
. The equality operator==
returnsfalse
if either operand isNaN
, and the inequality operator!=
returnstrue
if either operand isNaN
.
...
Code Block | ||
---|---|---|
| ||
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""); } } } |
Compliant Solution
...
Code Block | ||
---|---|---|
| ||
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""); } } } |
Risk Assessment
Comparisons with NaN
values may lead to unexpected results.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[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 07. Floating Point (FLP) FLP03-J. Use the strictfp modifier for floating point calculation consistency