The number hierarchy provides a common protocol for many numeric types. Smalltalk automatically converts between internal representations and provides unlimited precision integer arithmetic.
The most useful numeric classes are:
Smalltalks numeric classes make good use of polymorphism in the language:
instances of all numeric classes may be used interchangable in most
operations (for some, it does not make sense).
Also, results of arithmetic (and other) operations are converted as
appropriate. For example, executing:
(send the message 'divide by 3' to the integer '1')
will return a fractional result, represented by an instance of
1 / 3
Fraction
.
Integer
itself, but instead
of one of its subclasses, SmallInteger
or LargeInteger
.
SmallInteger
represents integers which fit into one
machine word (typically 32 bit (*)).
Storage of smallIntegers is very space efficient: in contrast to all other objects, smallIntegers are technically not represented by a pointer to the object, but instead the value is encoded in the pointer itself. Since one bit is required to distinguish smallIntegers from object references, one bit is lost for the storage of the integers value. Therefore, the smallInteger range is typically only -2^30 to 2^30-1.
LargeInteger
represents integers which are out
of the valid smallInteger range. They can represent arbitrary values
(i.e. beside memory limitations, the valid range of largeIntegers is not
limited).
(1 / 3) * 3 = 1
while the corresponding float operation:
(1 / 33) asFloat * 33
may return 0.999999... on some systems due to rounding errors.
Beside memory limitations, the precision of fractional numbers is unlimited.
double
implementation.
Typically, the precision of floats is some 15 digits - but you should not depend on this being true for all implementations. See the C-compilers documentation of your actual system for more information.
'goodies/Numeric-Complex.st'
.
Notes:
(*)
Actually, one bit is lost for implementation reasons. Therefore, the number of bits in a smallInteger is usually 31. (for details, see object representation)
Copyright © Claus Gittinger Development & Consulting, all rights reserved
(cg@ssw.de)