Java Reference
In-Depth Information
< Day Day Up >
Puzzle 2: Time for a Change
Consider the following word problem:
Tom goes to the auto parts store to buy a spark plug that costs $1.10, but all he has in his
wallet are two-dollar bills. How much change should he get if he pays for the spark plug with
a two-dollar bill?
Here is a program that attempts to solve the word problem. What does it print?
public class Change {
public static void main(String args[]) {
System.out.println(2.00 - 1.10);
}
}
Solution 2: Time for a Change
Naively, you might expect the program to print 0.90 , but how could it know that you wanted two
digits after the decimal point? If you know something about the rules for converting double values
to strings, which are specified by the documentation for Double.toString [Java-API] , you know
that the program prints the shortest decimal fraction sufficient to distinguish the double value from
its nearest neighbor, with at least one digit before and after the decimal point. It seems reasonable,
then, that the program should print 0.9 . Reasonable, perhaps, but not correct. If you ran the
program, you found that it prints 0.8999999999999999 .
The problem is that the number 1.1 can't be represented exactly as a double , so it is represented by
the closest double value. The program subtracts this value from 2. Unfortunately, the result of this
calculation is not the closest double value to 0.9. The shortest representation of the resulting
double value is the hideous number that you see printed.
More generally, the problem is that not all decimals can be represented exactly using binary
floating-point. If you are using release 5.0 or a later release, you might be tempted to fix the
program by using the printf facility to set the precision of the output:
// Poor solution - still uses binary floating-point!
 
 
Search WWH ::




Custom Search