Common Lisp/Advanced topics/Numbers

< Common Lisp < Advanced topics

Common Lisp has much more support for performing number-crunching tasks than most programming languages. This is achieved by having support for large integers, rational numbers, and complex numbers, as well as many functions to work on them.

Types of numbers

The hierarchy of the number type is as follows:

Fixnums and Bignums

Fixnums are integers which are not too large and can be manipulated very efficiently. Which numbers are considered fixnums is implementation-dependant, but all integers in [-215,215-1] are guaranteed to be such.

Bignums are integers which are not fixnums. Their size is limited by the amount of memory allocated for Lisp, and as such they can be really large. Operations on them are significantly slower than on fixnums. Of course, that doesn't make them less useful.


Ratios

Ratios represent the ratio of two integers. They have the form numerator/denominator. The function / which performs division always produces ratios when its arguments are integers or ratios. For example (/ 1 2) will result in 1/2, not 0.5. Other arithmetic operations also work fine with ratios.

Floats

Float is short for floating-point number, a datatype used to represent non-integer numbers in most programming languages. There are four kinds of floats in Common Lisp, which provide increasing precision (implementation-dependent). By default, implementations assume short floats, which have limited precision. To input a more precise float, other textual notations must be used, e.g., "1.0d0" for a double-float.

Complex

Complex is a datatype for representing complex numbers. The notation for complexes is #C(real imaginary). Real and imaginary parts are both either rational or floating-point. The operations that can be performed on complexes include all arithmetic operations and also many other functions which can be extended to complex numbers (such as exponentiation and logarithm).

Numeric Operations

The following functions are defined for all kinds of numbers:

The following functions are defined for specific kinds of numbers:

Comparison of numbers

The following functions can be used for comparison of numbers. Each of these functions accepts any number of arguments.

Numeric type manipulation

These functions are used to convert numbers from one type to another.

Predicate returns a non-nil result if it's true and nil if it is false.

See also

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.