...
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
.
Problems Because this "unordered property" is often unexpected, 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 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 may produce unexpected results.
Noncompliant Code Example
This noncompliant code example attempts a direct comparison with NaN
. As per the semantics of 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 equalresult is NaN" message is never printed.
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) { // comparison is always false! System.out.println("Bothresult areis equalNaN"); } } } |
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 when input is infinity if (Double.isNaN(result)) { System.out.println("Bothresult areis equalNaN"); } } } |
Risk Assessment
Comparisons with NaN
values can lead to unexpected results.
...