(^600) | Multidimensional Arrays and Numeric Computation
cannot be stored in our system, so what should we do? To be consistent with our response to
underflow, we could set the result to 9999 109 (the maximum representable value in this case).
Yet this strategy seems intuitively wrong. The alternative is to stop with an error message.
In Java, if an overflow occurs, the result is set to a special value called a signed infinity.If
an underflow occurs, the result is set to a signed zero. No exception is thrown in either case.
Although here we are discussing problems with floating-point numbers, note that integer
numbers can also overflow both negatively and positively. All implementations of Java ignore
integer overflow and underflow.To see how your system handles this situation, try adding 1 to
abytevariable that has been set to 127 and adding1toabytevariable that has been set to128.
Sometimes you can avoid overflow by arranging computations carefully. Suppose you
want to know how many different five-card poker hands can be dealt from a deck of cards.
Here we are looking for the number of combinationsof 52 cards taken 5 at a time. The stan-
dard mathematical formula for the number of combinations of nthings taken rat a time is
We could write a method factorialand place this formula in an assignment statement:
hands = factorial(52) / (factorial(5) * factorial(47));
The only problem is that 52! is a very large number (approximately 8.0658 1067 ), as is
47! (approximately 2.5862 1059 ). Both of these numbers are well beyond the capacity of
the JVM to represent exactly (52! requires 68 digits of precision). Even though we can repre-
sent them as floating-point numbers, most of the precision will be lost. By rearranging the
calculations, however, we can achieve an exact result with any integral type with nine or more
digits of precision (with intin Java). How? Consider that most of the multiplications in com-
puting 52! are canceled when the product is divided by 47!
52
547
52 51 50 49 48 47 46 45 44
5 4 3 2 1 47 46 45 44
!
!!×
= ×××××××××
()×××××××××()
K
K
n
rn r
!
!!( − )
9999 109
1000 109
9999000 1018 = 9999 1021
T
E
A
M
F
L
Y
Team-Fly®