Java Reference
In-Depth Information
provided by these types. For example, cryptography requires very large prime
numbers. As many as 2000 bits are used for the public/private key encryption
algorithms.
Floating-point values can represent large values but with limited precision.
The double type contains a 53-bit signed significand, which translates to 15 to
17 digits decimal precision. As we discussed in Chapter 2, it is often the case that
a finite number of digits in the binary base cannot represent a finite fraction in a
decimal value (1/10 is a typical example). So there can be a loss of precision for a
decimal value in floating-point format. Techniques to minimize and quantify the
accumulation of such errors over repeated calculations are available from error
analysis methods. A brute force approach, however, is simply to use extremely
high precision number representations that avoid the error build up altogether.
Financial calculations might need to use this approach, for example. Some math-
ematical exercises, such as calculating
π
to higher and higher precision, require
indefinitely wide fractional values.
For applications like these that require very large integer values and extremely
precise decimal values, the package java.math provides the BigInteger and
BigDecimal classes. Instances of these classes hold values of arbitrary preci-
sion. The values internally are immutable . Like String objects, once created,
they cannot change.
Since the object values are immutable, any operation on a BigInteger or
BigDecimal value can only return a new instance of the class. This is something
to consider when implementing algorithms with these classes that involve many
operations. Unneeded values should be de-referenced so that the garbage collector
can retrieve the memory space. Of course, operations with such classes are much
slower than those with primitive types.
In the following two sections we briefly describe these two classes. See the
Java 2 API Specifications for details about their methods [1]. See also the topic by
Mak for a more extensive discussion of these classes and for code that provides
additional mathematical functions with them [8].
10.13.1 BigInteger
The BigInteger class contains methods that provide all the basic arithmetic
operations such as add, subtract, multiply, and divide for indefinitely long integer
values. For example,
BigInteger bi1 = new BigInteger
( " 1143209523490543953412323238479 " );
BigInteger bi2 = new BigInteger
( " 34548738754398454599999997876786578479 " );
BigInteger bi3 = bi2.add (bi1); // = bi2 + bi1
BigInteger bi4 = bi2.divide (bi1); // = bi2 / bi1
Search WWH ::




Custom Search