Java Reference

In-Depth Information

Number”, and from then on your results are garbage. Division
x/0D

where
x
is nonzero produces either
Double.POSITIVE_INFINITY
or

Double.NEGATIVE_INFINITY
, and from then on your results are garbage.

Do not divide by 0, except for fun.

•
%
:
Remainder
. e.g
5.2 % 5
evaluates to
0.20000000000000018
. (You

would expect it to evaluate to
0.2
, but roundoff error is involved.)

The arithmetic relations
<
,
<=
,
>
, and
>=
can be used on values of type
dou-

ble
. For example,
1.3241 < 1.3241001
evaluates to
tru
e.

The operators
==
and
!=
can also be used with
double
operands. However,

these operators are rarely used because
double
values are only approximations.

Rather than checking for equality, one usually checks whether two
double
val-

ues are “close enough” —i.e. whether their absolute difference is small enough.

Precedence and associativity of double operators

The double operators have the same precedence and associativity properties

as their
int
counterparts. See Sec. 6.1.

Discussion

Type
double
is not as simple and straightforward as the above introduction

might indicate. This is because
double
numbers are only finite approximations

to real numbers. For example, the value of
Math.PI
, the closest possible approx-

imation to the ratio of the circumference of a circle to its diameter, is

3.141592653589793

but actually the fractional part of this ratio is not finite but goes on forever. It

does not even repeat (e.g. the rational number
1/4
can be written as
.25000...
;

the fraction consists of a non-repeating part
25
followed by a part,
0
, which

repeats forever).

Further, literals (like
3.141592653589793
) are written in decimal, but they

are stored in the computer in binary, and the conversion from decimal to binary

is another source of error.

Finally,
double
operations cannot be exact. For example:

(1D / 48D) * 48D
is printed as
1.0
, but

(1D / 49D) * 49D
is printed as
0.9999999999999999
.

So these two expressions are not equal in
double
arithmetic. Run this loop below

and analyze its output to see some of the approximations that go on. Because

double
values are only approximations, do not write a loop whose loop counter

is a
double
.

Search WWH ::

Custom Search