Programming and Problem Solving with Java

(やまだぃちぅ) #1
12.5 F l o ating-Point Numbers | 601

So, we really have to compute only


hands = 52 51 50 49 48 / factorial(5);


which means the numerator is 311,875,200 and the denominator is 120. If we have nine or
more digits of precision, we get an exact answer: 2,598,960 poker hands.


Cancellation Error Another type of error that can happen with floating-point numbers is a can-


cellation error, a form of representational error that occurs when we add or subtract numbers
of widely differing magnitudes. Let’s look at an example:


(1 + 0.00001234 1) = 0.00001234

The laws of arithmetic say this equation should be true. But is it true if the computer does
the arithmetic?


To four digits, the sum is 1,000  10 ^3. Now the computer subtracts 1:


The result is 0, not .00001234.
Sometimes you can avoid adding two floating-point numbers that are drastically different
in size by carefully arranging the calculations. Suppose a problem requires many small float-
ing-point numbers to be added to one large floating-point number. The result will be more
accurate if the code first sums the smaller numbers to obtain a larger number and then adds
the sum to the large number.


1000  10 ^3

 1000  10 ^3

0

100000000  10 ^8

 1234  10 ^8

100001234  10 ^8
Free download pdf