Java Reference
In-Depth Information
can never be true. Instead, the methods
Float.isNaN(float)
and
Double.isNaN(double)
must be used:
public
public static
static
void
void
main
(
String
[]
argv
) {
double
double
d
=
123
;
double
double
e
=
0
;
iif
(
d
/
e
==
Double
.
POSITIVE_INFINITY
)
System
.
out
.
println
(
"Check for POSITIVE_INFINITY works"
);
double
double
s
=
Math
.
sqrt
(-
1
);
iif
(
s
==
Double
.
NaN
)
System
.
out
.
println
(
"Comparison with NaN incorrectly returns true"
);
iif
(
Double
.
isNaN
(
s
))
System
.
out
.
println
(
"Double.isNaN() correctly returns true"
);
}
Note that this, by itself, is not sufficient to ensure that floating-point calculations have been
done with adequate accuracy. For example, the following program demonstrates a contrived
calculation—Heron's formula for the area of a triangle—both in
float
and in
double
. The
double values are correct, but the floating-point value comes out as zero due to rounding er-
rors. This happens because, in Java, operations involving only
float
values are performed as
32-bit calculations. Related languages such as C automatically promote these to double dur-
ing the computation, which can eliminate some loss of accuracy. Let's take a look:
public
public class
class
Heron
Heron
{
public
public static
void
main
(
String
[]
args
) {
// Sides for triangle in float
float
static
void
float
af
,
bf
,
cf
;
float
float
sf
,
areaf
;
// Ditto in double
double
double
ad
,
bd
,
cd
;
double
double
sd
,
aread
;
// Area of triangle in float
af
=
12345679.0f
;
bf
=
12345678.0f
;
cf
=
1.01233995f
;
sf
= (
af
+
bf
+
cf
)/
2.0f
;
areaf
= (
float
float
)
Math
.
sqrt
(
sf
* (
sf
-
af
) * (
sf
-
bf
) * (
sf
-
cf
));
System
.
out
.
println
(
"Single precision: "
+
areaf
);