BigNumber
The T3 VM's basic numeric type is the integer type. While this is largely adequate for writing interactive fiction, it's sometimes useful to have access to floating-point and high-precision integer arithmetic. The BigNumber type provides this functionality.
BigNumber can represent values with enormous precision, storing up to 65,000 decimal digits in a value; and can represent a huge range of values, with absolute values up to 1032767 and down to 10-32767. These limits are so extreme that practically real-world calculations will bump up against them. Furthermore, the BigNumber type can store values with whatever precision is actually required for each particular value, up to the limits; a program can use this flexibility to strike the balance it requires between numerical precision and performance.
For reasons that are probably obvious, the more precision a BigNumber value stores, the more memory it uses and the more time it takes to perform calculations with the number. BigNumber lets the programmer determine how much precision to use, so that the programmer can balance the degree of numerical precision against the cost in performance.
Note that the BigNumber type is not the "double" or IEEE floating point type that readers might have encountered in other programming languages. The BigNumber type is actually a custom type implemented entirely in the T3 VM. This has several advantages over "doubles":
- BigNumber is portable to any computer, and behaves exactly the same way on every computer. Doubles tend to have subtle but sometimes vexing variations from one computer to another.
- BigNumber uses a decimal rather than binary encoding, which means that any value that can be written in a decimal format can be represented exactly without rounding error. In contrast, some values that can be represented exactly in decimal can't be represented exactly in a binary encoding. For example, 1/5 is an endlessly repeating bit pattern in binary, much as 1/3 is an endless sequence in decimal (0.333333...); this surprises many people, because 1/5 is such a nice, round value - 0.2 - in decimal. This mismatch between what can be represented exactly in the two numbering systems can lead to the accumulation of unexpected rounding errors - unexpected because the intermediate values all look nice and exact when written in decimal. Using a decimal encoding, as BigNumber does, eliminates this potential confusion.
- BigNumber allows for effectively unlimited precision. Doubles have a fixed - and relatively small - precision. The nearly unlimited precision of BigNumber allows calculations involving very large integers, for example, or precise calculations where very large and very small values are combined.
(We shouldn't make it sound like BigNumber is better in every respect; doubles do have some advantages of their own, the foremost being better performance. This is partly because the algorithms for doing arithmetic are simpler for a fixed-precision type than for a varying-precision type, but the bigger reason is that doubles are implemented in hardware on many platforms. The performance trade-offs we have to make for BigNumber seem reasonable, though, given the type of application TADS is designed for. And it's rather neat to be able to calculate pi to a thousand digits with a couple of lines of code.)
Working with BigNumber values
You must #include <bignum.h> in your source files to use the BigNumber class. This file defines the BigNumber class interface.
You can write a BigNumber value as a floating-point constant. This is a numeric constant that contains a decimal point or an exponent, or both. The syntax is:
[ digit ... ] . [ digit ... ] [ ( E|e ) [ +|- ] digit ... ]
For example:
x = 3.14159265;
This syntax actually creates a BigNumber object that represents the given number. The compiler assigns the BigNumber's precision based on the number of significant digits in the constant value: this is the number of digits, ignoring leading zeros. For example, 0.00001 has only one digit of precision, since the leading zeroes are ignored, whereas 0.00001000 has a precision of four digits, since trailing zeroes are significant. The one exception to the leading-zero rule is that if the value is actually zero, all of the zeroes in the constant are significant: so 0.0000000 has a precision of 8 digits.
You can also use the new operator to create a BigNumber. Pass the value for the number either as an integer or as a character string. You can optionally specify the precision to use for the value; if you don't specify a precision, the system infers a precision from the value. If the source value is a string, the implied precision is the number of significant digits, the same as for a constant BigNumber value; if the source is an integer, the default precision is 32 digits.
x = new BigNumber(100); x = new BigNumber(100, 10); // set precision to 10 digits y = new BigNumber('3.14159265'); z = new BigNumber('1.06e-30'); z = new BigNumber('1.06e-30', 8); // precision is 8 digits
If you specify a string value, you can use a decimal point, and you can also use an 'E' to specify a base-ten exponent. So, the fourth value above should be read as 1.06×10-30.
Using the new operator has the advantage that you can explicitly specify the precision you want for the new value. If you do, it overrides the default precision that would otherwise be inferred from the source value.
You can perform addition, subtraction, multiplication, division, and negation on BigNumber values using the standard operators. You can also use integer values with BigNumber values in calculations, although the BigNumber value must always be the first operand in an expression involving both a BigNumber and an integer.
x = y + z; x = (y + z) * (y - z) / 2;
Similarly, you can compare BigNumber values using the normal comparison operators:
if (x > y) // ...
You can convert a BigNumber to a string using the toString() function in the tads-gen intrinsic function set. toString() uses a default formatting, though, so if you want control over the format, you should use the formatString() method of the BigNumber object itself.
You can convert a BigNumber to a regular integer value using the toInteger() function from the tads-gen function set. Note that toInteger() throws an error if passed a BigNumber value that's too large to represent as a 32-bit integer. The integer type can only store values from -2,147,483,648 to +2,147,483,647. toInteger() rounds numbers with fractional parts to the nearest integer.
You can't use operators other than those listed above with BigNumber values. You can't use a BigNumber as an operand for any of the bitwise operators (&, |, ~). You also can't use a BigNumber with the integer modulo operator (%), but you can obtain similar functionality from the divideBy() method.
You can't use BigNumber values in function and method calls that require integer arguments. You must explicitly convert a BigNumber value to an integer with the toInteger() function if you want to pass it to a method or function that takes an integer value; the compiler does not perform these conversions for you automatically.
Because BigNumber values are, for most purposes, simply object references, you can use them where you can use other objects; you can, for example, store a BigNumber in a list, or assign it to an object property.
Note that the compiler doesn't perform constant folding on expressions involving BigNumbers values. This means that an expression like the following will result in a run-time calculation being performed every time it's evaluated:
#define PI 3.14159265 x = PI/4;
Calling methods on BigNumber values
The BigNumber class provides a number of methods for manipulating values. Note that all of the methods that perform calculations return new BigNumber values. A BigNumber object's value is immutable once the object is created, so all calculations performed on these objects return new objects representing the result values.
These functions are all methods called on a BigNumber object. For example, to calculate the absolute value of a BigNumber value x, we would code this:
y = x.getAbs();
Some of the methods take an argument giving a value to be combined with the target number. For example, to get the remainder of dividing 10 by 3, we'd write this:
x = new BigNumber('10.0000'); y = new BigNumber('3.00000'); rem = x.divideBy(y)[2]; // second list item is remainder
BigNumber methods
arccosine()
arcsine()
arctangent()
copySignFrom(x)
cosh()
cosine()
degreesToRadians()
divideBy(x)
Note that the quotient returned from divideBy() is not necessarily equal to the whole part of the result of the division (/) operator applied to the same values. If the precision of the result (which is, as with all calculations, equal to the larger of the precisions of the operands) is insufficient to represent exactly the integer quotient result, the quotient returned from this function will be rounded differently from the quotient returned by the division operator. The division operator always rounds its result to the nearest
equalRound(num)
expE()
formatString(maxDigits, flags?, wholePlaces?, fracDigits?, expDigits?, leadFiller?)
maxDigits specifies the maximum number of digits to display in the formatted number; this is an upper bound only, and doesn't force a minimum number of digits. If necessary, the function uses scientific notation to make the number fit in the requested number of digits.
wholePlaces specifies the minimum number of places to show before the decimal point; if the number doesn't fill all of the requested places, the function inserts leading spaces (before the sign character, if any).
fracDigits specifies the number of digits to display after the decimal point. This specifies the maximum to display, and also the minimum; if the number doesn't have enough digits to display, the method adds trailing zeroes, and if there are more digits than fracDigits allows, the method rounds the value for display.
expDigits is the number of digits to display in the exponent; leading zeroes are inserted if necessary to fill the requested number of places.
Each of wholePlaces, fracDigits, and expDigits can be specified as -1, which tells the method to use the default value, which is simply the number of digits actually needed for the respective parts.
leadFiller, if specified, gives a string that is used instead of spaces to fill the beginning of the string, if required to satisfy the wholePlaces argument. This argument is ignored if its value is nil. If a string value is provided for this argument, the characters of the string are inserted, one at a time, to fill out the wholePlaces requirement; if the end of the string is reached before the full set of padding characters is inserted, the function starts over again at the beginning of the string. For example, to insert alternating asterisks and pound signs, you would specify '*#' for this argument.
flags is a combination of the following bit-flag values (combined with the bit-wise OR operator, |):
- BignumSign - always show a sign character. Normally, if the number is positive, the function omits the sign character. If this flag is specified, a + sign is shown for a positive number.
- BignumPosSpace - if the number is positive and this flag is set, the function inserts a leading space. (If BignumSign is specified, this flag is ignored.) This function can be used to ensure that positive and negative numbers fill the same number of character positions, even when you don't want to use a + sign with positive numbers.
- BignumExp - always show the number in exponential format (scientific notation). If this is not included, the function shows the number without an exponent if it will fit in maxDigits digits.
- BignumExpSign - always show a sign in the exponent. If this is included, a positive exponent will be shown with a + sign. This flag is ignored unless an exponent is displayed (so specifying this flag doesn't force an exponent to be displayed).
- BignumLeadingZero - always show a zero before the decimal point. This is only important when the number's absolute value is between 0 and 1, and an exponent isn't displayed; without this flag, no digits will precede the decimal point for such values (so 0.25 would be formatted as simply '.25').
- BignumPoint - always show a decimal point. If the number has no fractional digits to display, and this flag is included, a trailing decimal point is displayed. Without this flag, no decimal point is displayed if no digits are displayed after the decimal point.
- BignumCommas - show commas to set off thousands, millions, billions, and so on. This flag has no effect if the number is shown in scientific notation. Commas don't count against the maxDigits or wholePlaces limits. However, commas do count for leading filler, which ensures that a column of numbers formatted with filler and commas will line up properly.
- BignumEuroStyle - use European-style formatting: use periods instead of commas to set off thousands, millions, etc., and use a comma instead of a period to indicate the decimal point.
getAbs()
getCeil()
getE(digits)
x = BigNumber.getE(10);
The BigNumber class internally caches the value of e to the highest precision calculated so far during the program's execution, so this routine only needs to compute the value when it is called with a higher precision than that of the previously cached value.
getFloor()
getFraction()
getPi(digits)
x = BigNumber.getPi(10);
The BigNumber class internally caches the value of pi to the highest precision calculated so far during the program's execution, so this routine only needs to compute the value when it is called with a higher precision than that of the cached value.
getPrecision()
getScale()
getWhole()
isNegative()
log10()
logE()
negate()
radiansToDegrees()
raiseToPower(y)
roundToDecimal(places)
scaleTen(x)
setPrecision(digits)
sine()
Note that the input value must be expressed in radians. If you are working in degrees, you can convert to radians by multiplying your degree values by (pi/180), since 180 degress equals pi radians. For convenience, you can use the degreesToRadians() function to perform this conversion.
Note also that this remainder calculation's precision is limited by the precision of the original number itself, so a very large number with insufficient precision to represent at least a few digits after the decimal point (1.234e27, for example) will encounter a possibly significant amount of rounding error, which will affect the accuracy of the result. This should almost never be a problem in practice, because there is usually little reason to compute angle values outside of plus or minus a few times pi, but users should keep this in mind if they are using very large numbers and the trigonometric functions yield unexpected or inaccurate results.
sinh()
sqrt()
tangent()
Note that the tangent of (2n+1)*pi/2, where n is any integer, (i.e., any odd multiple of pi/2) is undefined, and that the limit approaching these values is plus or minus infinity. The BigNumber class internally calculates the tangent as the sine divided by the cosine, and as a result it is possible to generate a divide-by-zero exception by evaluating the tangent at one of these values. However, in most cases, because the input value cannot be exactly an odd multiple of pi/2 (because it isn't even theoretically possible to represent pi exactly with a finite number of decimal digits), the tangent will return a number with a very large absolute value.
tanh()
Precision and Scale
Each floating-point value that BigNumber represents has two important attributes apart from its value: precision and scale. For the most part, these are internal attributes that you can ignore; however, in certain cases, it's useful to know how BigNumber uses these internally.
The scale of a BigNumber value is a multiplier that determines how large the number really is. A BigNumber value stores a scale so that a very large or very small number can be represented compactly, without storing all of the digits that would be necessary to write out the number in decimal format. This is the same idea as writing a number in scientific notation, which represents a number as a value between 1 and 10 multiplied by ten raised to a power; for example, we could write four hundred fifty billion as 450,000,000,000, or more compactly in scientific notation as 4.5e11 (the "e" means "times ten to the power of the number that follows", so this means "4.5 times 1011"; note that 1011 is one hundred billion). When we write a number in scientific notation, we need only write the significant digits, and can elide the trailing zeroes of a very large number. We can also use scientific notation to write numbers with very small absolute values, by using a negative exponent: 9.7e-9 is 9.7 times 10-9; 10-9 is 1/109, or one one-billionth.
The precision of a BigNumber value is simply the number of decimal digits that the value actually stores. A number's precision determines how many distinct values it can have; the higher the precision, the more values it can store, and hence the finer the distinctions it can make between adjacent representable values. The precision is independent of the scale; if you create a BigNumber value with only one digit of precision, it's not limited to representing the values -9 through +9, because the scale can allow it take on larger or smaller values. So, you can represent arbitrarily large values regardless of a number's precision; however, the precision limits the number of distinct values the number can represent, so, for example, with one digit of precision, the next representable value after 8000 is 9000.
When you create a BigNumber value, you can explicitly assign it a precision by passing a precision specifier to the constructor. If you don't specify a precision, BigNumber will use a default precision. If you create a BigNumber value from an integer, the default precision is 32 digits. If you create a BigNumber value from a string, the precision is exactly enough to store the value's significant digits. A significant digit is a non-zero digit, or a zero that follows a non-zero digit. Here are some examples:
- '0012' has two significant digits (the leading zeroes are ignored).
- '1.2000' has five significant digits (the trailing zeroes are significant because they follow non-zero digits).
- '.00012' has two significant digits (the leading zeroes are ignored, even though they follow the decimal point).
- '000.00012' has two significant digits (leading zeroes are ignored, whether they appear before or after the decimal point).
- '1.00012' has six significant digits (the zeroes after the decimal point are significant because they follow a non-zero digit).
- '3.20e06' has three significant digits (the digits of the exponent, if specified, are not relevant to the number's precision).
When you use BigNumber values in calculations, the result is almost every case has the same precision as the value operated upon; in the case of calculations involving two or more operands, the result has precision equal to the greatest of the precisions of the operands. For example, if you add a number with three digits of precision to a number with eight digits of precision, the result will have eight digits of precision. This has the desirable effect of preserving the precision of your values in arithmetic, so that the precision you choose for your input data values is carried forward throughout your calculations. For example, consider this calculation:
x = new BigNumber('3.1415'); y = new BigNumber('0.000111'); z = x + y;
The exact arithmetic value of this calculation would be 3.1416111, but this is not the value that ends up in z, because the precision of the operands limits the precision of the result. The precision of x is 5, because it is created from a string with five significant digits. The precision of y is 3. The result of the addition will have a precision of 5, because that is the larger of the two input precisions. So, the result value stored in z will be 3.1416 - the additional two digits of y are dropped, because they cannot be represented in the result value's 5 digits of precision.
Precision limitations are fairly intuitive when the precision lost is after the decimal point, but note that digits can also be dropped before a decimal point. Consider this calculation:
x = new BigNumber('7.25e3'); y = new BigNumber('122'); z = x + y;
The value of x is 7.25e3, or 7250; this value has three digits of precision. The value of y also has three digits of precision. The exact result of the calculation is 7372, but the value stored in z will be 7370: the last digit of y is dropped because the result doesn't have enough precision to represent it.
Note that calculations will in most cases round their result values when they must drop precision from operand values. For example:
x = new BigNumber('7.25e3'); y = new BigNumber('127'); z = x + y;
The exact result would be 7377, but the value stored in z will be 7380: the last digit of y is dropped, but the system rounds up the last digit retained because the dropped digit is 5 or higher (in this case, 7).
Sample application: exorcising parasitic users
Apart from the obvious numerical applications, the BigNumber package can be useful if your computer is taken over by a hostile, parasitic, pure-energy life form capable of transferring itself between human and computer hosts. A quick survey of the literature will reveal that the best tactic against this type of infection is to command the computer to calculate a transcendental number (pi, for example) to the last digit. Computers are unable to comprehend the concept of irrational numbers, since they are so very rational, so such a calculation so preoccupies the computer that the unwanted life form is unable to get any CPU time and eventually flees the computer in frustration.
While BigNumber doesn't provide a dedicated syntax for computing transcendental numbers "to the last digit," you can still consume copious amounts of CPU time by asking it to compute a value to a large finite number of digits, such as
x = BigNumber.getPi(512);
This will consume about twenty minutes on a Pentium III at 400 MHz. (It only takes about 90 seconds on a Pentium D at 3.2 GHz, though, so you might have to increase the number of digits on a fast machine.) If the parasitic entity is especially tenacious, or tries to shut down life support, it might be necessary to go out to a thousand or so digits.
Note that this technique isn't effective against conventional computer viruses, so users might want to try one of the popular anti-virus software packages before attempting this solution.