Java Reference
In-Depth Information
$
java numbers.FractMult
3.33
0.0
3.333333333333333
3.3333333333333335
3
$
You should also beware of the possibility of numeric overflow, and avoid this optimization if
you cannot guarantee that the multiplication by the numerator will not overflow.
Ensuring the Accuracy of Floating-Point Numbers
Problem
You want to know if a floating-point computation generated a sensible result.
Solution
Compare with the
INFINITY
constants, and use
isNaN()
to check for “not a number.”
Fixed-point operations that can do things like divide by zero result in Java notifying you ab-
ruptly by throwing an exception. This is because integer division by zero is considered a
lo-
gic error
.
Floating-point operations, however, do not throw an exception because they are defined over
an (almost) infinite range of values. Instead, they signal errors by producing the constant
POSITIVE_INFINITY
if you divide a positive floating-point number by zero, the constant
NEGATIVE_INFINITY
if you divide a negative floating-point value by zero, and
NaN
(Not a
Number) if you otherwise generate an invalid result. Values for these three public constants
are defined in both the
Float
and the
Double
wrapper classes. The value
NaN
has the unusual
property that it is not equal to itself (i.e.,
NaN
!=
NaN
). Thus, it would hardly make sense to
compare a (possibly suspect) number against
NaN
, because the following expression can nev-
er be true:
x == NaN