# (lispkit math)

Library `(lispkit math)`

defines functions on numbers. Numbers are arranged into a tower of subtypes in which each level is a subset of the level above it:

number

complex number

real number

rational number

integer

For example, 3 is an integer. Therefore 3 is also a rational, a real, and a complex number. These types are defined by the predicates `number?`

, `complex?`

, `real?`

, `rational?`

, and `integer?`

.

There is no simple relationship between a number’s type and its representation inside a computer. Scheme’s numerical operations treat numbers as abstract data, as independent of their representation as possible.

## Numerical constants

The constant pi.

Euler's number, i.e. the base of the natural logarithm.

Number of bits used to represent fixnum numbers (typically 64).

Greatest fixnum value (typically 9223372036854775807).

Smallest fixnum value (typically -9223372036854775808).

Bound to the appropriate machine epsilon for the hardware representation of flonum numbers, i.e. the positive difference between 1.0 and the next greater representable number.

This value compares greater than or equal to all finite floating-point numbers, but less than infinity.

This value compares less than or equal to all positive floating-point numbers, but greater than zero.

## Predicates

These numerical type predicates can be applied to any kind of argument, including non-numbers. They return `#t`

if the object is of the named type, and otherwise they return `#f`

. In general, if a type predicate is true of a number then all higher type predicates are also true of that number. Consequently, if a type predicate is false of a number, then all lower type predicates are also false of that number.

If *z* is a complex number, then `(real? z)`

is true if and only if `(zero? (imag-part z))`

is true. If *x* is an inexact real number, then `(integer? x)`

is true if and only if `(= x (round x))`

.

The numbers `+inf.0`

, `-inf.0`

, and `+nan.0`

are real but not rational.

Returns `#t`

if object *obj* is a fixnum; otherwise returns `#f`

. A fixnum is an exact integer that is small enough to fit in a machine word. LispKit fixnums are 64-bit words. Fixnums are signed and encoded using 2’s complement.

Returns `#t`

if object `obj`

is a fractional number, i.e. a rational number which isn't an integer.

Returns `#t`

if object *obj* is a large integer number, i.e. an integer which isn't a fixnum.

Returns `#t`

if object *obj* is a floating-point number.

Returns `#t`

if object *obj* is a complex floating-point number.

These numerical predicates provide tests for the exactness of a quantity. For any Scheme number, precisely one of `exact?`

and `inexact?`

is true.

Returns `#t`

if *obj* is both exact and an integer; otherwise returns `#f`

.

The `finite?`

procedure returns `#t`

on all real numbers except `+inf.0`

, `-inf.0`

, and `+nan.0`

, and on complex numbers if their real and imaginary parts are both finite. Otherwise it returns `#f`

.

The `infinite?`

procedure returns `#t`

on the real numbers `+inf.0`

and `-inf.0`

, and on complex numbers if their real or imaginary parts or both are infinite. Otherwise it returns `#f`

.

The `nan?`

procedure returns `#t`

on `+nan.0`

, and on complex numbers if their real or imaginary parts or both are `+nan.0`

. Otherwise it returns `#f`

.

Returns `#t`

if number *x* is positive, i.e. `x > 0`

.

Returns `#t`

if number *x* is negative, i.e. `x < 0`

.

Returns `#t`

if number *z* is zero, i.e. `z = 0`

.

Returns `#t`

if the integer number *n* is even.

Returns `#t`

if the integer number *n* is odd.

## Exactness and rounding

Scheme distinguishes between numbers that are represented exactly and those that might not be. This distinction is orthogonal to the dimension of type. A number is exact if it was written as an exact constant or was derived from exact numbers using only exact operations. A number is inexact if it was written as an inexact constant, if it was derived using inexact ingredients, or if it was derived using inexact operations.

Rational operations such as `+`

should always produce exact results when given exact arguments. If the operation is unable to produce an exact result, then it either reports the violation of an implementation restriction or it silently coerces its result to an inexact value.

The procedure `inexact`

returns an inexact representation of *z*. The value returned is the inexact number that is numerically closest to the argument. For inexact arguments, the result is the same as the argument. For exact complex numbers, the result is a complex number whose real and imaginary parts are the result of applying inexact to the real and imaginary parts of the argument, respectively. If an exact argument has no reasonably close inexact equivalent (in the sense of `=`

), then a violation of an implementation restriction may be reported.

The procedure `exact`

returns an exact representation of *z*. The value returned is the exact number that is numerically closest to the argument. For exact arguments, the result is the same as the argument. For inexact non-integral real arguments, the function may return a rational approximation. For inexact complex arguments, the result is a complex number whose real and imaginary parts are the result of applying exact to the real and imaginary parts of the argument, respectively. If an inexact argument has no reasonably close exact equivalent, (in the sense of `=`

), then a violation of an implementation restriction may be reported.

These procedures implement the natural one-to-one correspondence between `exact`

and `inexact`

integers throughout an implementation-dependent range.

Procedure `approximate`

approximates floating-point number *x* returning a rational number which differs at most *delta* from *x*.

The `rationalize`

procedure returns the simplest rational number differing from *x* by no more than *y*. A rational number *r1* is simpler than another rational number *r2* if *r1 = p1/q1* and *r2 = p2/q2* (in lowest terms) and |p1| ≤ |p2| and |q1| ≤ |q2|. Thus `3/5`

is simpler than `4/7`

. Although not all rationals are comparable in this ordering (consider `2/7`

and `3/5`

), any interval contains a rational number that is simpler than every other rational number in that interval (the simpler `2/5`

lies between `2/7`

and `3/5`

). Note that `0 = 0/1`

is the simplest rational of all.

These procedures return integers. `floor`

returns the largest integer not larger than *x*. `ceiling`

returns the smallest integer not smaller than *x*. `truncate`

returns the integer closest to *x* whose absolute value is not larger than the absolute value of *x*. `round`

returns the closest integer to *x*, rounding to even when *x* is halfway between two integers.

If the argument to one of these procedures is inexact, then the result will also be inexact. If an exact value is needed, the result can be passed to the `exact`

procedure. If the argument is *infinite* or a *NaN*, then it is returned.

## Operations

These procedures return the sum or product of their arguments.

With two or more arguments, these procedures return the difference or quotient of their arguments, associating to the left. With one argument, however, they return the additive or multiplicative inverse of their argument.

It is an error if any argument of `/`

other than the first is an exact zero. If the first argument is an exact zero, the implementation may return an exact zero unless one of the other arguments is a NaN.

These procedures return `#t`

if their arguments are (respectively): equal, monotonically increasing, monotonically decreasing, monotonically non-decreasing, or monotonically non-increasing, and `#f`

otherwise. If any of the arguments are `+nan.0`

, all the predicates return `#f`

. They do not distinguish between inexact zero and inexact negative zero.

These procedures return the maximum or minimum of their arguments.

If any argument is inexact, then the result will also be inexact (unless the procedure can prove that the inaccuracy is not large enough to affect the result, which is possible only in unusual implementations). If `min`

or `max`

is used to compare numbers of mixed exactness, and the numerical value of the result cannot be represented as an inexact number without loss of accuracy, then the procedure reports an implementation restriction.

The `abs`

procedure returns the absolute value of its argument *x*.

Returns the square of *z*. This is equivalent to *(* z z)*.

Returns the principal square root of *z*. The result will have either a positive real part, or a zero real part and a non-negative imaginary part.

Returns two non-negative exact integers *s* and *r* where *k = s^2+r* and *k < (s+1)^2*.

Returns *z1* raised to the power *z2*. For non-zero *z1*, this is *z1^z2 = e^(z2 log z1)*. The value of 0^z is `1`

if `(zero? z)`

, 0 if `(real-part z)`

is positive, and an error otherwise. Similarly for 0.0z, with inexact results.

These procedures compute the usual transcendental functions. The `log`

procedure computes the natural logarithm of *z* (not the base-ten logarithm) if a single argument is given, or the base-*z2* logarithm of *z1* if two arguments are given. The `asin`

, `acos`

, and `atan`

procedures compute `arc-sine`

, `arc-cosine`

, and `arc-tangent`

, respectively. The two-argument variant of `atan`

computes `(angle (make-rectangular x y))`

.

## Division and remainder

These procedures return the greatest common divisor (`gcd`

) or least common multiple (`lcm`

) of their arguments. The result is always non-negative.

These procedures implement number-theoretic integer division. It is an error if `n2`

is zero. `truncate/`

returns two integers; the other two procedures return an integer. All the procedures compute a quotient `nq`

and remainder `nr`

such that `n1 = n2 * nq + nr`

. The three procedures are defined as follows:

The remainder `nr`

is determined by the choice of integer `nq`

: `nr = n1 − n2 * nq`

where `nq = truncate(n1/n2)`

.

For any of the operators, and for integers `n1`

and `n2`

with `n2`

not equal to 0:

provided all numbers involved in that computation are exact.

These procedures implement number-theoretic integer division. It is an error if `n2`

is zero. `floor/`

returns two integers; the other two procedures return an integer. All the procedures compute a quotient `nq`

and remainder `nr`

such that `n1 = n2 * nq + nr`

. The three procedures are defined as follows:

The remainder `nr`

is determined by the choice of integer `nq`

: `nr = n1 − n2 * nq`

where `nq = floor(n1/n2)`

.

For any of the operators, and for integers `n1`

and `n2`

with `n2`

not equal to 0:

provided all numbers involved in that computation are exact.

The `quotient`

and `remainder`

procedures are equivalent to `truncate-quotient`

and `truncate-remainder`

, respectively, and `modulo`

is equivalent to `floor-remainder`

. These procedures are provided for backward compatibility with earlier versions of the Scheme language specification.

## Fractional numbers

These procedures return the numerator or denominator of their rational number `q`

. The result is computed as if the argument was represented as a fraction in lowest terms. The denominator is always positive. The denominator of 0 is defined to be 1.

## Complex numbers

Returns the complex number *x1 + x2 * i*. Since in LispKit, all complex numbers are inexact, `make-rectangular`

returns an inexact complex number for all *x1* and *x2*.

Returns a complex number *z* such that *z = x1 * e^(x2 * i)*, i.e. *x1* is the magnitude of the complex number. The `make-polar`

procedure may return an inexact complex number even if its arguments are exact.

Returns the real part of the given complex number *z*.

Returns the imaginary part of the given complex number *z*.

Returns the magnitude of the given complex number *z*. Assuming *z = x1 * e^(x2 * i)*, `magnitude`

returns *x1*. The `magnitude`

procedure is the same as `abs`

for a real argument.

Returns the `angle`

of the given complex number *z*. The angle is a floating-point number between `-pi`

and `pi`

.

## Random numbers

If called without any arguments, `random`

returns a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). If *max* is provided and is an exact integer, `random`

returns a random exact integer between 0 (inclusive) and *max* (exclusive). If *max* is inexact, the random number returned by `random`

is a floating-point number between 0.0 (inclusive) and *max* (exclusive). If *min* is provided, it is used instead of zero as the included lower-bound of the random number range. If one of *min* and *max* are inexact, the result is inexact. *max* needs to be greater than *min*.

## String representation

It is an error if *radix* is not one of 2, 8, 10, or 16. The procedure `number->string`

takes a number *z* and a *radix* and returns as a string an external representation of the given number in the given radix such that

is true. It is an error if no possible result makes this expression true. If omitted, radix defaults to 10.

If *z* is inexact, the radix is 10, and the above expression can be satisfied by a result that contains a decimal point, then the result contains a decimal point and is expressed using the minimum number of digits (exclusive of exponent and trailing zeroes) needed to make the above expression true. Otherwise, the format of the result is unspecified. The result returned by `number->string`

never contains an explicit radix prefix.

The error case can occur only when *z* is not a complex number or is a complex number with a non-rational real or imaginary part. If *z* is an inexact number and the radix is 10, then the above expression is normally satisfied by a result containing a decimal point. The unspecified case allows for infinities, NaNs, and unusual representations.

The string representation can be customized via parameters *len*, *prec*, and *noexp*. The absolute value of fixnum *len* determines the length of the string representation in characters. If *len* is negative, then the number is left-aligned; for positive *len*, it is right-aligned; if *len* is zero, no padding is done. *prec* determines the precision of flonum and complex values (i.e. the number of significant digits; default is 16). *noexp* is a boolean for disabling the exponential notation (if *noexp* is set to `#t`

).

Returns a number of the maximally precise representation expressed by the given string *str*. It is an error if *radix* is not 2, 8, 10, or 16. If supplied, *radix* is a default radix that will be overridden if an explicit radix prefix is present in string (e.g. `"#o177"`

). If *radix* is not supplied, then the default radix is 10. If string *str* is not a syntactically valid notation for a number, or would result in a number that cannot be represented, then `string->number`

returns `#f`

. An error is never signaled due to the content of string.

## Bitwise operations

The following bitwise functions operate on integers including fixnums and bignums.

Returns the bitwise complement of *n*; i.e. all 1 bits are changed to 0 bits and all 0 bits to 1 bits.

Returns the *bitwise and* of the given integer arguments *n ...*.

Returns the *bitwise inclusive or* of the given integer arguments *n ...*.

Returns the *bitwise exclusive or (xor)* of the given integer arguments *n ...*.

Merge the integers *n* and *m*, via integer *mask* determining from which integer to take each bit. That is, if the *k*-th bit of *mask* is 0, then the *k*-th bit of the result is the *k*-th bit of *n*, otherwise the *k*-th bit of *m*. `bitwise-if`

is defined in the following way:

Returns the population count of 1's if *n >= 0*, or 0's, if *n < 0*. The result is always non-negative. The R6RS analogue `bitwise-bit-count`

procedure is incompatible as it applies `bitwise-not`

to the population count before returning it if *n* is negative.

Returns the number of bits needed to represent *n*, i.e.

The result is always non-negative. For non-negative *n*, this is the number of bits needed to represent *n* in an unsigned binary representation. For all *n*, `(+ 1 (integer-length i))`

is the number of bits needed to represent *n* in a signed two's-complement representation.

Returns the index of the least significant 1 bit in the two's complement representation of *n*. If *n* is 0, then −1 is returned.

*k* must be non-negative. The `bit-set?`

procedure returns `#t`

if the *k*-th bit is 1 in the two's complement representation of *n*, and `#f`

otherwise. This is the result of the following computation:

*k* must be non-negative, and *b* must be either 0 or 1. The `copy-bit`

procedure returns the result of replacing the *k*-th bit of *n* by the *k*-th bit of *b*, which is the result of the following computation:

If *count > 0*, shifts integer *n* left by *count* bits; otherwise, shifts fixnum *n* right by *count* bits. In general, this procedure returns the result of the following computation: `(floor (* n (expt 2 count)))`

.

Returns the result of arithmetically shifting *n* to the left by *count* bits. *count* must be non-negative. The `arithmetic-shift-left`

procedure behaves the same as `arithmetic-shift`

.

Returns the result of arithmetically shifting *n* to the right by *count* bits. *count* must be non-negative. `(arithmetic-shift-right n m)`

behaves the same as `(arithmetic-shift n (fx- m))`

.

## Fixnum operations

LispKit supports arbitrarily large exact integers. Internally, it has two different representations, one for smaller integers and one for the rest. These are colloquially known as *fixnums* and *bignums* respectively. In LispKit, a *fixnum* is represented as a 64 bit signed integer which is encoded using two-complement.

Fixnum operations perform integer arithmetic on their fixnum arguments. If any argument is not a fixnum, or if the mathematical result is not representable as a fixnum, it is an error. In particular, this means that fixnum operations may return a mathematically incorrect fixnum in these situations without raising an error.

`integer->fixnum`

coerces a given integer *n* into a fixnum. If *n* is a fixnum already, *n* is returned by `integer->fixnum`

. If *n* is a bignum, then the first word of the bignum is returned as the result of `integer->fixnum`

.

These procedures return the sum, the difference, the product and the quotient of their fixnum arguments *n m ...*. These procedures may overflow without reporting an error. `(fx- n)`

is negating `n`

.

These procedures implement the comparison predicates for fixnums. `fx=`

returns `#t`

if all provided fixnums are equal. `fx<`

returns `#t`

if all provided fixnums are strictly monotonically increasing. `fx>`

returns `#t`

if all provided fixnums are strictly monotonically decreasing. `fx<=`

returns `#t`

if all provided fixnums are monotonically increasing. `fx>=`

returns `#t`

if all provided fixnums are monotonically decreasing.

Increments the fixnum *n* by one and returns the value. This procedure may overflow without raising an error.

Decrements the fixnum *n* by one and returns the value. This procedure may overflow without raising an error.

Returns `#t`

if fixnum *n* equals to 0.

Returns `#t`

if fixnum *n* is positive, i.e. *n > 0*.

Returns `#t`

if fixnum *n* is negative, i.e. *n < 0*.

Returns the absolute value of its fixnum argument *n*.

This procedure returns a value *r* such that the following equation holds: *n = m * q + r* where *q* is the largest number of multiples of *m* that will fit inside *n*. The sign of *m* gets ignored. This means that `(fxremainder n m)`

and `(fxremainder n (- m))`

always return the same answer.

This procedure computes a remainder similar to `(fxremainder n m)`

, but when `(fxremainder n m)`

has a different sign than *m*, `(fxmodulo n m)`

returns `(+ (fxremainder n m) m)`

instead.

Approximates the square root *s* of fixnum *n* such that *s* is the biggest fixnum for which *s × s ≤ n*.

Returns the *bitwise-logical inverse* for fixnum *n*.

Returns the *bitwise-logical and* for *n* and *m*.

Returns the *bitwise-logical inclusive or* for *n* and *m*.

Returns the *bitwise-logical exclusive or (xor)* for *n* and *m*.

Merges the bit sequences *n* and *m*, with bit sequence *mask* determining from which sequence to take each bit. That is, if the *k*-th bit of *mask* is 1, then the *k*-th bit of the result is the *k*-th bit of *n*, otherwise it's the *k*-th bit of *m*.

`fxif`

can be implemented via `(fxior (fxand mask n) (fxand (fxnot mask) m)))`

.

If *count > 0*, shifts fixnum *n* left by *count* bits; otherwise, shifts fixnum *n* right by *count* bits. The absolute value of *count* must be less than `fx-width`

.

`fxarithmetic-shift`

can be implemented via `(floor (fx* n (expt 2 m)))`

if this computes to a fixnum.

Returns the result of arithmetically shifting *n* to the left by *count* bits. *count* must be non-negative, and less than `fx-width`

. The `fxarithmetic-shift-left`

procedure behaves the same as `fxarithmetic-shift`

.

Returns the result of arithmetically shifting *n* to the right by *count* bits. *count* must be non-negative, and less than `fx-width`

. `(fxarithmetic-shift-right n m)`

behaves the same as `(fxarithmetic-shift n (fx- m))`

.

Returns the result of logically shifting *n* to the right by *count* bits. *count* must be non-negative, and less than `fx-width`

.

If *n* is non-negative, this procedure returns the number of 1 bits in the two's complement representation of *n*. Otherwise, it returns the result of the following computation: `(fxnot (fxbit-count (fxnot n)))`

.

Returns the number of bits needed to represent *n* if it is positive, and the number of bits needed to represent `(fxnot n)`

if it is negative, which is the fixnum result of the following computation:

Returns the index of the least significant 1 bit in the two's complement representation of *n*. If *n* is 0, then −1 is returned.

*k* must be non-negative and less than `fx-width`

. The `fxbit-set?`

procedure returns `#t`

if the *k*-th bit is 1 in the two's complement representation of *n*, and `#f`

otherwise. This is the fixnum result of the following computation:

*k* must be non-negative and less than `fx-width`

. *b* must be 0 or 1. The `fxcopy-bit`

procedure returns the result of replacing the *k*-th bit of *n* by *b*, which is the result of the following computation:

Returns the minimum of the provided fixnums *n, m ...*.

Returns the maximum of the provided fixnums *n, m ...*.

Returns a random number between fixnum *min* (inclusive) and fixnum *max* (exclusive). If *min* is not provided, then 0 is assumed to be the minimum bound. *max* is required to be greater than *min*. If called without any arguments, `fxrandom`

returns a random fixnum number from the full fixnum range.

## Floating-point operations

Returns *x* × 2^*n*, where *n* is a fixnum with an implementation-dependent range. The significand *x* is a flonum.

Returns the best flonum representation of real number *x*.

Returns the exponent of flonum *x* (using a base of 2).

Returns the significand of flonum *x*.

Returns the least representable flonum value that compares greater than flonum *x*.

Returns the greatest representable flonum value that compares less than flonum *x*.

These procedures return the flonum sum or product of their flonum arguments *x y ...*. In general, they return the flonum that best approximates the mathematical sum or product.

These procedures return the flonum difference or quotient of their flonum arguments *x ...*. In general, they return the flonum that best approximates the mathematical difference or quotient. `(fl- x)`

negates `x`

, `(fl/ x)`

is equivalent to `(fl/ 1.0 x)`

.

Returns `#t`

if *x = 0.0*, `#f`

otherwise.

Returns `#t`

if *x > 0.0*, `#f`

otherwise.

Returns `#t`

if *x < 0.0*, `#f`

otherwise.

These procedures implement the comparison predicates for flonums. `fl=`

returns `#t`

if all provided flonums are equal. `fl<`

returns `#t`

if all provided flonums are strictly monotonically increasing. `fl>`

returns `#t`

if all provided flonums are strictly monotonically decreasing. `fl<=`

returns `#t`

if all provided flonums are monotonically increasing. `fl>=`

returns `#t`

if all provided flonums are monotonically decreasing.

Returns the absolute value of *x* as a flonum.

Returns the minimum value of the provided flonum values *x ...*. If no arguments are provided, positive infinity is returned.

Returns the maximum value of the provided flonum values *x ...*. If no arguments are provided, negative infinity is returned.

Returns a random number between flonum *min* (inclusive) and flonum *max* (exclusive). If *min* is not provided, then 0.0 is assumed to be the minimum bound. *max* is required to be greater than *min*. If called without any arguments, `flrandom`

returns a random floating-point number from the interval `[0.0, 1.0[`

.

Last updated