Java Reference
In-Depth Information
1.4000000000000004
1.5000000000000004
1.6000000000000005
1.7000000000000006
1.8000000000000007
1.9000000000000008
2.000000000000001
The problem occurs because 0.1 cannot be stored exactly in base-2 (it produces a
repeating set of digits, just as one-third does in base-10). Each time through the loop
the error is compounded, which is why the roundoff error gets worse each time.
As another example, consider the task of adding together the values of a penny, a
nickel, a dime, and a quarter. If we use variables of type int , we will get an exact
answer regardless of the order in which we add the numbers:
int cents1 = 1 + 5 + 10 + 25;
int cents2 = 25 + 10 + 5 + 1;
System.out.println(cents1);
System.out.println(cents2);
The output of this code is as follows:
41
41
Regardless of the order, these numbers always add up to 41 cents. But suppose
that instead of thinking of these values as whole cents, we think of them as fractions
of a dollar that we store as double s:
double dollars1 = 0.01 + 0.05 + 0.10 + 0.25;
double dollars2 = 0.25 + 0.10 + 0.05 + 0.01;
System.out.println(dollars1);
System.out.println(dollars2);
This code has surprising output:
0.41000000000000003
0.41
Even though we are adding up exactly the same numbers, the fact that we add
them in a different order makes a difference. The reason is roundoff errors.
There are several lessons to draw from this:
Be aware that when you store floating-point values (e.g., double s), you are stor-
ing approximations and not exact values. If you need to store an exact value, store
it using type int .
 
Search WWH ::




Custom Search