Floating-point numbers can take on three exceptional values, infinity
, -infinity
and NaN
(not-a-number). These values are produced as a result of exceptional or otherwise unresolvable floating point operations. These exceptional values can also be obtained directly from user input through methods such as Double.valueOf(String s)
. Failure to detect and handle such exceptional values can result in inconsistent behavior.
NaN
values are particularly problematic because they are unordered. That is, the expression NaN == NaN
always returns false
(see guideline NUM10-J. Do not attempt comparisons with NaN). In general, any comparisons with NaN
return false
, and all arithmetic functions with one or more NaN
inputs produce NaN
as their output. Consequently, a single occurrence of a NaN
value can cause regressions within other code segments. This correctâ”and arguably desirableâ”behavior can cause unexpected results.
The method Double.valueOf(String s)
can return NaN
or an infinite double
, as specified by its contract. Programs should install checks to ensure that all floating point inputs (especially those obtained from the user) are free of unexpected exceptional values. The methods Double.isNaN(double d)
and Double.isInfinite(double d)
can be used for this purpose.
NaN
values are particularly problematic because they are unordered. That is, the expression NaN == NaN
always returns false
(see guideline NUM10-J. Do not attempt comparisons with NaN).
Noncompliant Code Example
...
Automated Detection
Automated detection is not feasible infeasible in the general case. It could be possible to develop a taint-like analysis that detects many interesting cases.
...