prev back next

Number classes

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:

Use the systemBrowser to have a more detailed look into the implementation.

Number

Number is the abstract superclass of all number-like objects. It provides methods which are independent of the actual numeric representation.

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:

	1 / 3
(send the message 'divide by 3' to the integer '1') will return a fractional result, represented by an instance of Fraction.

Integer

Integer is the abstract superclass of all integral number objects. There are no instances of Integer itself, but instead of one of its subclasses, SmallInteger or LargeInteger. Conversion between smallIntegers and largeIntegers is transparent; if some value cannot be represented as smallInteger, the system automatically creates a largeInteger object for it.

Fraction

Fractions are rational numbers, typically resulting from a division of two integers which does not give an integral result. In contrast to floatingPoint arithmetic, fractional arithmetic is exact. Therefore:
	(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.

Float

Floats are limited precision real numbers. The representation depends on the underlying machines and C-compilers double implementation.
On most modern systems, the IEEC representation is used.

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.

others

You can extent the Number hierarchy, by adding new classes which implement a certain minimum protocol (they should know how to perform some of the basic arithmetic operations, and how to be converted into other representations).
As an example, see the implementation of a complex class in the file '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)