Article Preview
Buy Now
| Print: | |
| PDF: |
Feature
Arbitrary Precision Numbers
Storing and performing math on larger numbers with improved accuracy
Issue: 3.1 (September/October 2004)
Author: Thomas Reed
Author Bio: Thomas Reed has been programming as a hobbyist for more than 20 years, and fell in love with the Mac in 1984.
Article Description: No description available.
Article Length (in bytes): 11,032
Starting Page Number: 34
RBD Number: 3116
Resource File(s):
3116.sit Updated: Wednesday, September 15, 2004 at 4:27 PM
Related Link(s): None
Known Limitations: None
Excerpt of article text...
The numeric types provided by modern computers cannot store a very large range of numbers. Long integers can store, at most, unsigned numbers up to around 4.29 billion, or +/-2.15 billion for signed numbers. Floating point numbers can store larger (and smaller) values than an integer, but their precision is very limited. You cannot rely on floating point numbers being exactly what you think they are. For many numbers, these limitations mean that the built-in numeric types are useless.
Fortunately, smart programmers have come up with an algorithm for "arbitrary precision" numbers, which can be very large or very small while also being extremely precise. The secret to arbitrary precision numbers is to store the number in some kind of string representation in which each digit is specified exactly. For example, a number could be represented by a string of bytes, each containing a value between 0 and 9.
Let's consider the way the BigNumber class, found in the sample project (download instructions reside on page 4), will store the number strings. BigNumber's constructor creates a MemoryBlock of 2 * maxSize bytes, where maxSize is the maximum desired number length, in terms of digit count. The first digit after the decimal point will be stored at the byte position maxSize, and the first digit before the decimal point will be stored at position maxSize-1. See Figure 1 for an example. Note that, although there is space in this structure for 2 * maxSize digits, we will only allow numbers with maxSize digits to be stored.
...End of Excerpt. Please purchase the magazine to read the full article.
Article copyrighted by REALbasic Developer magazine. All rights reserved.
|











