...
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 | ||
---|---|---|
| ||
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");
}
}
}
|
...
This compliant solution uses the method Double.isNaN()
to check whether the expression corresponds to a NaN
value.
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("result is NaN");
}
}
}
|
...
FE: Doomed test for equality to NaN | |
[JLS 2005] | |
[Seacord 2015] | NUM07-J. Do not attempt comparisons with NaN LiveLesson |
NUM06-J. Use the strictfp modifier for floating-point calculation consistency across platforms