Java Reference
In-Depth Information
PITFALL: Round-Off Errors in Floating-Point Numbers
For all practical purposes, floating-point numbers are only approximate quantities.
For example, in formal mathematics the floating-point number 1.0/3.0 is equal to
0.3333333...
where the three dots indicate that the 3 s go on forever. The computer stores numbers
in a format somewhat like this decimal representation, but it has room for only a
limited number of digits. If it can store only 10 digits after the decimal, then 1.0/3.0
is stored as
0.3333333333
with only 10 threes. Thus, 1.0/3.0 is stored as a number that is slightly smaller than
one-third. In other words, the value stored as 1.0/3.0 is only approximately equal to
one-third.
In reality, the computer stores numbers in binary notation, rather than in base 10
notation, but the principles are the same and the consequences are the same. Some
floating-point numbers lose accuracy when they are stored in the computer.
Floating-point numbers (like numbers of type double ) and integers (like numbers
of type int ) are stored differently. Floating-point numbers are, in effect, stored as
approximate quantities. Integers are stored as exact quantities. This difference some-
times can be subtle. For example, the numbers 42 and 42.0 are different in Java. The
whole number 42 is of type int and is an exact quantity. The number 42.0 is of type
double because it contains a fractional part (even though the fraction is 0 ), and so
42.0 is stored with only limited accuracy.
As a result of this limited accuracy, arithmetic done on floating-point numbers
only gives approximate results. Moreover, one can easily get results on floating-
point numbers that are very far from the true result you would obtain if the num-
bers could have unlimited accuracy (unlimited number of digits after the decimal
point). For example, if a banking program used numbers of type double to repre-
sent amounts of money and did not do sophisticated manipulations to preserve
accuracy, it would quickly bring the bank to ruin since the computed amounts of
money would frequently be very incorrect. Dealing with these inaccuracies in
floating-point numbers is part of the field of Numerical Analysis, a topic we will not
discuss in this topic. But, there is an easy way to obtain accuracy when dealing with
amounts of money: use integers instead of floating-point numbers (perhaps one
integer for the dollar amount and another integer for the cents amount).
Although the % operator is primarily used with integers, it can also be used with two
floating-point numbers, such as two values of type double . However, we will not dis-
cuss nor use % with floating-point numbers.
Search WWH ::




Custom Search