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 and the consequences are the same. Some fl oating-point
numbers lose accuracy when they are stored in the computer.
Floating-point numbers (such as numbers of type double ) and integers (such as
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
sometimes 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 fl oating-point numbers
only gives approximate results. Moreover, one can easily get results on fl oating-point
numbers that are very far from the true result you would obtain if the numbers could
have unlimited accuracy (unlimited number of digits after the decimal point). For
example, if a banking program used numbers of type double to represent 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 fre-
quently be very incorrect. Dealing with these inaccuracies in fl oating-point numbers
is part of the fi eld 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 fl oating-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
discuss nor use % with floating-point numbers.
 
Search WWH ::




Custom Search