Title

Numerics with Infinities

Author

Aubrey Jaffer

This SRFI is currently in ``draft'' status. To see an explanation of each status that a SRFI can hold, see here. It will remain in draft status until 2005/07/13, or as amended. To provide input on this SRFI, please mailto:srfi-70@srfi.schemers.org. See instructions here to subscribe to the list. You can access previous messages via the archive of the mailing list.

Abstract

Checks for division by zero (and their absence) remain one of the most common programming errors. In numerical code the conscientious programmer must deeply nest conditionals to assure that checks for zero preceed each division.

With infinities added to the number system we find that division by zero "works". It lets initialization of variables precede bounds checks and gives flexibility in placement of those checks. Limit and corner cases need not crash programs.

This SRFI reworks section 6.2 "Numbers" of R5RS to:

Issues

Rationale

Inexactness

Inexactness is as much a property of calculation as it is of data sources. A language having latent types does not obviate the programmer's expectation that a calculation involving transcendental functions should return an inexact result. To this end, two sentences are struck from the 6.2.2 "Exactness" section:
An operation may, however, return an exact result if it can prove that the value of the result is unaffected by the inexactness of its arguments. For example, multiplication of any number by an exact zero may produce an exact zero result, even if the other argument is inexact.
By those sentences, inexactness is a contagious property of all numbers; except 0, the only number whose exactness is contagious! This conflicts with the statement earlier in 6.2.2:
... Thus inexactness is a contagious property of a number.
For code expecting inexact arguments, such an exception creates a latent bug which may be exercised only rarely. SRFI-63 is a case in point:
When assigning an exact number to an inexact array-type, the procedure may report a violation of an implementation restriction.
Also struck is the last sentence of section 6.2.1 Numerical types:
... In order to catch uses of inexact numbers where exact numbers are required, Scheme explicitly distinguishes exact from inexact numbers. This distinction is orthogonal to the dimension of type.
which seems to imply that each internal number representation is instantiated both in exact and inexact forms.

Integer versus Exact

R5RS describes quotient, remainder, and modulo as integer operations. They are required to work for integers, whether exact or inexact. The use of N for names of their arguments similarly declares gcd, lcm, odd?, and even? to be integer operations.

But these operations become poorly behaved for inexacts outside the range where each integer has a unique representation. For instance, all large magnitude IEEE-754 numbers are integers and even (a multiple of 2) because the radix, and hence the scaling factors, are even.

Distinguishing these functions on the basis of integer arguments overlooks their generalizations to exact rational numbers:

    modulo(x/y, w/z) = modulo(lcm(y, z)*x/y, lcm(y, z)*w/z)/lcm(y, z)
    remainder(x/y, w/z) = remainder(lcm(y, z)*x/y, lcm(y, z)*w/z)/lcm(y, z)
    gcd(x/y, w/z) = gcd(x, w)/lcm(y, z)
    lcm(x/y, w/z) = lcm(x, w)/gcd(y, z)
Common-Lisp mod and rem are general to rational and real arguments:
(mod 2/3 1/5)               ==>  1/15
(mod .666 1/5)              ==>  0.065999985
This SRFI extends quotient, remainder, and modulo to work for exact rationals and inexact reals.

In inexact calculations, one is not guaranteed that results will yield integers. Thus odd? and even? will sometimes signal errors or give false negatives when inexact integer calculations are slightly wide of their integer marks. If these predicates instead accept only exact integers, then their behavior is predictable; and conversion from inexacts to exacts must be explicit.

Infinities

This SRFI introduces inexact real infinities for implementations with inexact numbers. These infinities arise as the result of: This SRFI attempts to strike a balance between tolerance and signaling of range errors. Having 1/0 and -1/0 allows one level of calculation to be executed before bounds checking. Subsequent numerical calculations on infinities can signal an error or return a non-real infinity: 0/0. 0/0 can be considered an error waiting to happen.

This SRFI mandates the real infinities for implementations with inexacts, but leaves to the implementations the decision of whether to implement 0/0 or not.

Are there predicates for infinities?
The new `finite?' predicate will return `#f' for infinities, `#t' for other numbers;
`real?' will return `#f' for `0/0'; and
the two real infinities have opposite signs.
What about exact infinities?
1/0 + 1 = 1/0; the only numbers which can be their own increments are inexact numbers.
Can infinities be the only inexacts an implementation supports?
That would mean that any divisions not returning exact numbers would either signal an error or return an infinity. Most of the transcendental functions would return only infinities.
Are real infinities rational?
No; (mathematical) rational numbers have non-zero denominators.
Are real infinities integers?
Because they are not rational they cannot be integers.
What about complex (non-real) infinities?
Infinities in rectangular notation leads to strange beasts like 1/0+5i. I know of no mathematical system having such numbers. Polar notation allows an infinitude of numbers having infinite magnitude and finite angle. Multiplication and division of complex infinities would work, but at the price of forcing their representations to be polar.
What about +0.0 and -0.0?
Dealing with zero is certainly thorny; but having more varieties of zero does not make dealing with unsigned zero any easier. The limit procedure provides a mathematical alternative to non-standard analysis half-measures.

0/0 = 0/0

The bad boy of IEEE Standard 754 is not-a-number, which does not equal itself. This was a cute trick to provide a means for software to detect it without requiring literal constants or new comparison primitives.

But reflexive identity is one of the most basic mathematical principals. In implementations where inexact numbers are boxed

    (let ((narn (/ 0.0 0.0))) (eq? narn narn))
is required to be true, which forces eqv? to return true in the same situation:
Eq?'s behavior on numbers and characters is implementation-dependent, but it will always return either true or false, and will return true only when eqv? would also return true.
The `=' procedure is similarly forced to find narn equal to itself.

sqrt

The description of sqrt has been wrong since R3RS. Prepending "For real z" to the second sentence corrects it.

expt

In R3RS and R4RS the description of expt is very simple:
procedure: expt z1 z2

Returns z1 raised to the power z2:

z_1z_2 = ez_2 log z_1

00 is defined to be equal to 1.

The simplicity is nice, but in the absence of infinities, the straightforward scheme implementation
    (define (expt b x) (exp (* x (log b))))
is incapable of operating when b is zero.

According to G. Sussman, the change in R5RS to

0z is 1 if z = 0 and 0 otherwise.
was "... attempting to follow Common Lisp and APL when it came to boundary conditions and branch cuts."

About expt, Common-Lisp says:

expt is defined as bx = ex log b. This defines the principal values precisely. The range of expt is the entire complex plane. Regarded as a function of x, with b fixed, there is no branch cut. Regarded as a function of b, with x fixed, there is in general a branch cut along the negative real axis, continuous with quadrant II. The domain excludes the origin. By definition, 00=1. If b=0 and the real part of x is strictly positive, then bx=0. For all other values of x, 0x is an error.
With log(0) being -1/0, and because exp(-1/0) is 0.0, Common-Lisp behavior would follow from:
    (define (expt b x) (exp (* x (log b))))
except when b is zero.

With (log 0) being -1/0, the product of x and -1/0 determines the trajectory of exp. Exp's domain repeats every 2*pi radians in the imaginary direction. This multiplication rotates the negative real infinity. If it rotates into a direction other than pure real, then the limit of (exp (* b (log x))) does not exist (because of the 2*pi periodicity).

Common-Lisp's criterion of testing the sign of the real part of x can be seen as snapping the direction of the product to either a positive or negative real infinity.

(exp (* 1 -1/0))            ==>  0.0
(exp (* -1 -1/0))           ==>  1/0
Because Common-Lisp doesn't have explicit infinities, it signals an error for negative real parts of x. The Common-Lisp behavior except, for (expt 0.0 0.0), can be produced by
(define (expt z1 z2) (exp (* (if (zero? z1) (real-part z2) z2) (log z1))))

Having real infinities enables these definitions to work when z1 is zero. Although the simpler definition is mathematically satisfying, the "real-part" variant allows (expt 0.0 z) to return something other than 0/0 when the exponent has small imaginary parts due to inexact inaccuracies.

The approach of this SRFI is to use this latter definition without excepting (expt 0.0 0.0), which either returns 0/0 or signals an error. (expt 0.0 z), where z has a negative real-part, returns 1/0, where Common-Lisp signals an error. Otherwise the behavior is the same as Common-Lisp's expt.

Inexactness Considered Harmful?

Sebastian Egner, Richard Kelsey, Michael Sperber:
Cleaning up the Tower: Numbers in Scheme,
The 2004 Scheme Workshop, Snowbird, Utah, October 2004.

Abstract

The R5RS specification of numerical operations leads to unportable and intransparent behavior of programs. Specifically, the notion of "exact/inexact numbers" and the misleading distinction between "real" and "rational" numbers are two primary sources of confusion. Consequently, the way R5RS organizes numbers is significantly less useful than it could be. Based on this diagnosis, we propose to abandon the concept of exact/inexact numbers from Scheme altogether. In this paper, we examine designs in which exact and inexact rounding operations are explicitly separated, while there is no distinction between exact and inexact numbers. Through examining alternatives and practical ramifications, we arrive at an alternative proposal for the design of the numerical operations in Scheme.
In my view the essential distinction of number-theoretic operations is that they are exact, not that they are integer as R5RS holds. This SRFI rectifies the problem by extending most of the affected procedures. Restricting the integer operations to exact integer arguments would also work.

Cleaning up the Tower demotes the exactness property relative to types while this SRFI promotes it. Yet both find that the exactness of procedures should play a more important role in determining the exactness of numerical results.

In their proposed system:

Any program that does not contain calls to floating-point operations always computes exactly and reproducibly, independent of the Scheme implementation it runs on.
This will require either As an author of a Scheme implementation, I find the first option unappealing; coding a complicated feature to solve a problem that the implementation doesn't have. If some feature must be jettisoned, then removing exact rational non-integers might be a simpler and less wrenching alternative than removing exactness as an organizing principle. Experience with SCM shows that the R5RS number system can work well without exact rational non-integers.

Full reproducibility will require extensive changes to R5RS:

The reproducibility condition is too strong; it needs restrictions so that it doesn't expose properties of the host file system.

Clean Infinities

The treatment of infinities by "Cleaning up the Tower" also differs from this SRFI.
... an exact division by zero is virtually always a symptom of a genuine programming error or of illegal input data, and the introduction of infinity will only mask this error.
This is not the case in the R5RS model, where substitution of exact for inexact does not change the computation.

The advantage of returning NaN instead of raising an error is that the computation still continues, postponing the interpretation of the results to a more convenient point in the program. In this way, NaN is quite useful in numerical computations.
While finding 1/0 and -1/0 to be very useful in computation, I cannot say the same for 0/0. It usually arises as the result of operating on a real infinity. Tolerating one error is useful; tolerating more than one error in a computation masks programming errors. That is why this SRFI leaves to the implementation whether to signal an error or return 0/0.
The problem with NaN is that the program control structure will mostly not recognize the NaN case explicitly. Assume we define comparisons with NaN always to result in #f, as IEEE 754 does, then
(do ((x NaN (+ x 1))) ((> x 10)))
will hang but
(do ((x NaN (+ x 1))) ((not (<= x 10))))
will stop, which is counter-intuitive and may be surprising.
Because it has no sensible place in the well ordering of real numbers, 0/0 (NaN) is not a real number. Thus it is an illegal argument to the comparison procedures `<', `<=', `>', and `>='; which should signal an error upon encountering it.
While +inf, -inf, and NaN are quite useful for inexact computations, there is a high price to pay when they are carried over into the exact world: The rational numbers must be extended by the special objects, and the usual algebraic laws will not hold for the extension anymore.
This need not be the case. This "high price" is a consequence of the proposed (section 5) "type permeability" kinds #2 and #3, which prohibit exact arguments to inexact procedures.

As shown earlier, infinities are always inexact. Infinities being inexact makes detecting them in exact calculations easier. Not only will the `finite?', `rational?', and `exact?' procedures return `#f' for infinities; but passing infinities to exact-only or integer-only procedures is an error.

The Limit

Many Scheme implementations treat an exact 0 as stronger than an inexact 0.0; returning 0 for (/ 0 0.0) while signaling an error for (/ 0.0 0). This leads to the use of exactness coercions to select behavior of `/' and `expt'; a practice which is very opaque.

Each implementation supporting flonums must decide how to evaluate (/ 0.0 0.0) and (expt 0.0 0.0) because those functions are mathematically ill-defined for all-zero arguments. Cases can be made for 1.0 and 0.0 because the limits of (/ x x) and (/ 0.0 x) are 1.0 and 0.0 respectively. But why are we statically determining behavior in a dynamic language? This SRFI introduces the `limit' procedure to produce the mathematically expected behavior of finite and infinite limits of functions.

Specification

Here is the text proposed to replace section "6.2 Numbers" of R5RS. Deleted text is marked with a line through it. Additions and changes are marked in red.
Note: The type restriction for the naming convention `r' is "exact rational number":
r, r1, ... rj, ...
exact rational number

6.2 Numbers

Numerical computation has traditionally been neglected by the Lisp community. Until Common Lisp there was no carefully thought out strategy for organizing numerical computation, and with the exception of the MacLisp system [Pitman83] little effort was made to execute numerical code efficiently. This report recognizes the excellent work of the Common Lisp committee and accepts many of their recommendations. In some ways this report simplifies and generalizes their proposals in a manner consistent with the purposes of Scheme.

It is important to distinguish between the mathematical numbers, the Scheme numbers that attempt to model them, the machine representations used to implement the Scheme numbers, and notations used to write numbers. This report uses the types number, complex, real, rational, and integer to refer to both mathematical numbers and Scheme numbers. Machine representations such as fixed point and floating point are referred to by names such as fixnum and flonum.

6.2.1 Numerical types

Mathematically, numbers may be arranged into a tower of subtypes in which each level is a subset of the level above it:

          number
          complex
          real
          rational
          integer

For example, 3 is an integer. Therefore 3 is also a rational, a real, and a complex. The same is true of the Scheme numbers that model 3. For Scheme numbers, 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. Although most implementations of Scheme will offer at least two different representations of 3, these different representations denote the same integer.

Scheme's numerical operations treat numbers as abstract data, as independent of their representation as possible. Although an implementation of Scheme may use fixnum, flonum, and perhaps other representations for numbers, this should not be apparent to a casual programmer writing simple programs.

It is necessary, however, to distinguish between numbers that are represented exactly and those that may not be. For example, indexes into data structures must be known exactly, as must some polynomial coefficients in a symbolic algebra system. On the other hand, the results of measurements are inherently inexact, and irrational numbers may be approximated by rational and therefore inexact approximations. In order to catch uses of inexact numbers where exact numbers are required, Scheme explicitly distinguishes exact from inexact numbers. This distinction is orthogonal to the dimension of type.

6.2.2 Exactness

Scheme numbers are either exact or inexact. 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 is infinite, if it was written as an inexact constant, if it was derived using inexact ingredients, or if it was derived using inexact operations. Thus inexactness is a contagious property of a number.

If two implementations produce exact results for a computation that did not involve inexact intermediate results, the two ultimate results will be mathematically equivalent. This is generally not true of computations involving inexact numbers since because approximate methods such as floating point arithmetic may be used, but it is the duty of each implementation to make the result as close as practical to the mathematically ideal result.

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 may either report the violation of an implementation restriction or it may silently coerce its result to an inexact value. See section 6.2.3 Implementation restrictions.

With the exception of inexact->exact, the operations described in this section must generally return inexact results when given any inexact arguments. An operation may, however, return an exact result if it can prove that the value of the result is unaffected by the inexactness of its arguments. For example, multiplication of any number by an exact zero may produce an exact zero result, even if the other argument is inexact.

6.2.2x Inexactness

Implementations of Scheme which implement inexact numbers must implement positive infinity and negative infinity as unique real inexact numbers.

An optional third infinity, which is not real, results when an infinity is an argument to a numerical function such that no number (including infinities) is the correct answer. An implementation may report a violation of an implementation restriction in any calculation for which the result would be an unreal infinity.

Implementations of Scheme which implement inexact numbers shall also provide the limit and finite? procedures.

Function: limit proc z1 z2
Function: limit proc -1/0
Function: limit proc 1/0

Proc must be a procedure taking a single inexact argument.

Limit computes the mathematical limit of proc as its argument approaches z1 from z1 + z2. Limit returns a complex number or real infinity if the limit exists; and `#f' otherwise.

(limit / 0 1.0e-9)                              ==>  1/0
(limit / 0 -1.0e-9)                             ==>  -1/0
(limit / -1/0)                                  ==>  0.0
(limit / 1/0)                                   ==>  0.0
(limit (lambda (x) (/ x x)) 0 1.0e-9)           ==>  1.0
(limit (lambda (x) (/ (log x) x)) 0 1.0e-9)     ==>  -1/0
(limit (lambda (x) (/ (log x) x)) 0 -1.0e-9)    ==>  #f
(limit (lambda (x) (/ x (log x))) 0 1.0e-9)     ==>  0.0
(limit sin 1/0)                                 ==>  #f
(limit (lambda (x) (sin (/ x))) 0 1.0e-9)       ==>  #f
(limit (lambda (x) (sin (/ x))) 0 -1.0e-9)      ==>  #f
(limit (lambda (x) (sin (/ x))) 1/0)            ==>  0.0
(limit (lambda (x) (/ (+ (exp (/ x)) 1))) 0 1.0e-9)
                                                ==>  0.0
(limit (lambda (x) (/ (+ (exp (/ x)) 1))) 0 -1.0e-9)
                                                ==>  1.0
(limit (lambda (x) (expt (tan x) (cos x))) (/ pi 2) 1.0e-9)
                                                ==>  1.0000000000000022

6.2.3 Implementation restrictions

Implementations of Scheme are not required to implement the whole tower of subtypes given in section 6.2.1 Numerical types, but they must implement a coherent subset consistent with both the purposes of the implementation and the spirit of the Scheme language. For example, an implementation in which all numbers are real may still be quite useful.

Implementations may also support only a limited range of numbers of any type, subject to the requirements of this section. The supported range for exact numbers of any type may be different from the supported range for inexact numbers of that type. For example, an implementation that uses flonums to represent all its inexact real numbers may support a practically unbounded range of exact integers and rationals while limiting the range of inexact reals (and therefore the range of inexact integers and rationals) to the dynamic range of the flonum format. Furthermore the gaps between the representable inexact integers and rationals are likely to be very large in such an implementation as the limits of this range are approached.

An implementation of Scheme must support exact integers throughout the range of numbers that may be used for indexes of lists, vectors, and strings or that may result from computing the length of a list, vector, or string. The length, vector-length, and string-length procedures must return an exact integer, and it is an error to use anything but an exact integer as an index. Furthermore any integer constant within the index range, if expressed by an exact integer syntax, will indeed be read as an exact integer, regardless of any implementation restrictions that may apply outside this range. Finally, the procedures listed below will always return an exact integer result provided all their arguments are exact integers and the mathematically expected result is representable as an exact integer within the implementation:


+            -             *
quotient     remainder     modulo
max          min           abs
numerator    denominator   gcd
lcm          floor         ceiling
truncate     round         rationalize
expt

Implementations are encouraged, but not required, to support exact integers and exact rationals of practically unlimited size and precision, and to implement the above procedures and the `/' procedure in such a way that they always return exact results when given exact arguments. If one of these procedures is unable to deliver an exact result when given exact arguments, then it may either report a violation of an implementation restriction or it may silently coerce its result to an inexact number. Such a coercion may cause an error later.

An implementation may use floating point and other approximate representation strategies for inexact numbers.

This report recommends, but does not require, that the IEEE 32-bit and 64-bit floating point standards be followed by implementations that use flonum representations, and that implementations using other representations should match or exceed the precision achievable using these floating point standards [IEEE].

In particular, implementations that use flonum representations must follow these rules: A flonum result must be represented with at least as much precision as is used to express any of the inexact arguments to that operation. It is desirable (but not required) for potentially inexact operations such as `sqrt', when applied to exact arguments, to produce exact answers whenever possible (for example the square root of an exact 4 ought to be an exact 2). If, however, an exact number is operated upon so as to produce an inexact result (as by `sqrt'), and if the result is represented as a flonum, then the most precise flonum format available must be used; but if the result is represented in some other way then the representation must have at least as much precision as the most precise flonum format available.

Although Scheme allows a variety of written notations for numbers, any particular implementation may support only some of them. For example, an implementation in which all numbers are real need not support the rectangular and polar notations for complex numbers. If an implementation encounters an exact numerical constant that it cannot represent as an exact number, then it may either report a violation of an implementation restriction or it may silently represent the constant by an inexact number.

6.2.4 Syntax of numerical constants

The syntax of the written representations for numbers is described formally in section 7.1.1 Lexical structure. Note that case is not significant in numerical constants.

A number may be written in binary, octal, decimal, or hexadecimal by the use of a radix prefix. The radix prefixes are `#b' (binary), `#o' (octal), `#d' (decimal), and `#x' (hexadecimal). With no radix prefix, a number is assumed to be expressed in decimal.

A numerical constant may be specified to be either exact or inexact by a prefix. The prefixes are `#e' for exact, and `#i' for inexact. An exactness prefix may appear before or after any radix prefix that is used. If the written representation of a number has no exactness prefix, the constant may be either inexact or exact. It is inexact if it contains a decimal point, an exponent, a "#" character in the place of a digit, or ends with "/0"; otherwise it is exact.

Negative infinity is written `-1/0' (or `#i-1/0'). Positive infinity is written `1/0' or `+1/0'. The (optional) non-real infinity is written `0/0'. Although the written forms of infinity look like exact rational numbers, infinities are neither exact nor rational.

In systems with inexact numbers of varying precisions it may be useful to specify the precision of a constant. For this purpose, numerical constants may be written with an exponent marker that indicates the desired precision of the inexact representation. The letters `s', `f', `d', and `l' specify the use of short, single, double, and long precision, respectively. (When fewer than four internal inexact representations exist, the four size specifications are mapped onto those available. For example, an implementation with two internal representations may map short and single together and long and double together.) In addition, the exponent marker `e' specifies the default precision for the implementation. The default precision has at least as much precision as double, but implementations may wish to allow this default to be set by the user.

3.14159265358979F0
       Round to single --- 3.141593
0.6L0
       Extend to long --- .600000000000000

6.2.5 Numerical operations

The reader is referred to section 1.3.3 Entry format for a summary of the naming conventions used to specify restrictions on the types of arguments to numerical routines.

The examples used in this section assume that any numerical constant written using an exact notation is indeed represented as an exact number. Some examples also assume that certain numerical constants written using an inexact notation can be represented without loss of accuracy; the inexact constants were chosen so that this is likely to be true in implementations that use flonums to represent inexact numbers.

procedure: number? obj
procedure: complex? obj
procedure: real? obj
procedure: rational? obj
procedure: integer? obj

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 an inexact 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

    (and (finite? x) (= x (round x)))
(complex? 3+4i)                        ==>  #t
(complex? 3)                           ==>  #t
(real? 3)                              ==>  #t
(real? -2.5+0.0i)                      ==>  #t
(real? #e1e10)                         ==>  #t
(rational? 6/10)                       ==>  #t
(rational? 6/3)                        ==>  #t
(integer? 3+0i)                        ==>  #t
(integer? 3.0)                         ==>  #t
(integer? 8/4)                         ==>  #t
(complex? 1/0)                         ==>  #t
(complex? 0/0)                         ==>  #t
(real? 0/0)                            ==>  #f
(real? -1/0)                           ==>  #t
(rational? 1/0)                        ==>  #f
(rational? 0/0)                        ==>  #f
(integer? -1/0)                        ==>  #f

Note: The behavior of these type predicates on inexact numbers is unreliable, since because any inaccuracy may affect the result.

Note: In many implementations the rational? procedure will be the same as real?, and the complex? procedure will be the same as number?, but unusual implementations may be able to represent some irrational numbers exactly or may extend the number system to support some kind of non-complex numbers.

procedure: exact? z
procedure: inexact? z

These numerical predicates provide tests for the exactness of a quantity. For any Scheme number, precisely one of these predicates is true.

(exact? 5)                   ==>  #t
(inexact? 1/0)               ==>  #t
(inexact? 0/0)               ==>  #t

procedure: = z1 z2 z3 ...
procedure: < x1 x2 x3 ...
procedure: > x1 x2 x3 ...
procedure: <= x1 x2 x3 ...
procedure: >= x1 x2 x3 ...

These procedures return #t if their arguments are (respectively): equal, monotonically increasing, monotonically decreasing, monotonically nondecreasing, or monotonically nonincreasing.

(= 1/0 1/0)                 ==>  #t
(= -1/0 -1/0)               ==>  #t
(= 0/0 0/0)                 ==>  #t
For any finite real number x:
(< -1/0 x 1/0))             ==>  #t
(> 1/0 x -1/0))             ==>  #t

These predicates are required to be transitive.

Note: The traditional implementations of these predicates in Lisp-like languages are not transitive.

Note: While it is not an error to compare inexact numbers using these predicates, the results may be unreliable because a small inaccuracy may affect the result; this is especially true of = and zero?. When in doubt, consult a numerical analyst.

library procedure: finite? z
library procedure: zero? z
library procedure: positive? x
library procedure: negative? x
library procedure: odd? n
library procedure: even? n

These numerical predicates test a number for a particular property, returning #t or #f. See note above.

(positive? 1/0)             ==>  #t
(negative? -1/0)            ==>  #t
(finite? -1/0)              ==>  #f
(finite? 0/0)               ==>  #f

library procedure: max x1 x2 ...
library procedure: min x1 x2 ...

These procedures return the maximum or minimum of their arguments.

(max 3 4)                              ==>  4    ; exact
(max 3.9 4)                            ==>  4.0  ; inexact
For any real number x:
(max 1/0 x)                            ==>  1/0
(min -1/0 x)                           ==>  -1/0

Note: 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 may report a violation of an implementation restriction.

procedure: + z1 ...
procedure: * z1 ...

These procedures return the sum or product of their arguments.

(+ 3 4)                                ==>  7
(+ 3)                                  ==>  3
(+)                                    ==>  0
(+ 1/0 1/0)                            ==>  1/0
(+ 1/0 -1/0)                           ==>  0/0

(* 4)                                  ==>  4
(*)                                    ==>  1
(* 5 1/0)                              ==>  1/0
(* -5 1/0)                             ==>  -1/0
(* 1/0 1/0)                            ==>  1/0
(* 1/0 -1/0)                           ==>  -1/0
(* 0 1/0)                              ==>  0/0
For any finite number z:
(+ 1/0 z)                              ==>  1/0
(+ -1/0 z)                             ==>  -1/0
For any number z:
(+ 0/0 z)                              ==>  0/0
(* 0/0 z)                              ==>  0/0

procedure: - z1 z2
procedure: - z
optional procedure: - z1 z2 ...
procedure: / z1 z2
procedure: / z
optional procedure: / z1 z2 ...

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.

(- 3 4)                                ==>  -1
(- 3 4 5)                              ==>  -6
(- 3)                                  ==>  -3
(- 1/0 1/0)                            ==>  0/0

(/ 3 4 5)                              ==>  3/20
(/ 3)                                  ==>  1/3
(/ 0.0)                                ==>  1/0
(/ 1.0 0)                              ==>  1/0
(/ -1 0.0)                             ==>  -1/0
(/ 1/0)                                ==>  0.0
(/ 0 0.0)                              ==>  0/0
(/ 0.0 0)                              ==>  0/0
(/ 0.0 0.0)                            ==>  0/0

library procedure: abs x

`Abs' returns the absolute value of its argument.

(abs -7)                               ==>  7
(abs -1/0)                             ==>  1/0

procedure: quotient n1 n2 x1 x2
procedure: remainder n1 n2 x1 x2
procedure: modulo n1 n2 x1 x2

These procedures implement number-theoretic (integer) division. x2 should be non-zero. All three procedures return integers. `quotient' returns an integer. If x1/x2 is an integer:

    (quotient x1 x2)                   ==> x1/x2
    (remainder x1 x2)                  ==> 0
    (modulo x1 x2)                     ==> 0

If x1/x2 is not an integer:

    (quotient x1 x2)                   ==> n_q
    (remainder x1 x2)                  ==> x_r
    (modulo x1 x2)                     ==> x_m

where n_q is x1/x2 rounded towards zero, 0 < |x_r| < |x2|, 0 < |x_m| < |x2|, x_r and x_m differ from x1 by a multiple of x2, x_r has the same sign as x1, and x_m has the same sign as x2.

From this we can conclude that for integers n1 and n2 with x2 not equal to 0,

     (= x1 (+ (* x2 (quotient x1 x2))
           (remainder x1 x2)))
                                       ==>  #t

provided all numbers involved in that computation are exact.

(modulo 13 4)                          ==>  1
(remainder 13 4)                       ==>  1

(modulo -13 4)                         ==>  3
(remainder -13 4)                      ==>  -1

(modulo 13 -4)                         ==>  -3
(remainder 13 -4)                      ==>  1

(modulo -13 -4)                        ==>  -1
(remainder -13 -4)                     ==>  -1

(remainder -13 -4.0)                   ==>  -1.0  ; inexact

(quotient 2/3 1/5)                     ==>  3
(modulo 2/3 1/5)                       ==>  1/15

(quotient .666 1/5)                    ==>  3
(modulo .666 1/5)                      ==>  65.99999999999995e-3

library procedure: gcd n1 r1 ...
library procedure: lcm n1 r1 ...

These procedures return the greatest common divisor or least common multiple of their arguments. The result is always non-negative.

For exact integer arguments, these procedures are the familiar number theoretic operators:

(gcd 32 -36)                           ==>  4
(gcd)                                  ==>  0
(lcm 32 -36)                           ==>  288
(lcm)                                  ==>  1
For exact rational arguments, gcd returns the largest rational that divides into each of its arguments a whole number of times, while lcm returns the smallest rational that is an integer multiple of its arguments.
(gcd 1/6 1/4)                          ==>  1/12
(lcm 1/6 1/4)                          ==>  1/2
(gcd 1/6 5/4)                          ==>  1/12
(lcm 1/6 5/4)                          ==>  5/2

procedure: numerator q
procedure: denominator q

These procedures return the numerator or denominator of their argument; 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.

(numerator (/ 6 4))                    ==>  3
(denominator (/ 6 4))                  ==>  2
(denominator
  (exact->inexact (/ 6 4)))            ==> 2.0

procedure: floor x
procedure: ceiling x
procedure: truncate x
procedure: round x

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.

Rationale: `Round' rounds to even for consistency with the default rounding mode specified by the IEEE floating point standard.

Note: 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 should be passed to the `inexact->exact' procedure.

(floor -4.3)                           ==>  -5.0
(ceiling -4.3)                         ==>  -4.0
(truncate -4.3)                        ==>  -4.0
(round -4.3)                           ==>  -4.0

(floor 3.5)                            ==>  3.0
(ceiling 3.5)                          ==>  4.0
(truncate 3.5)                         ==>  3.0
(round 3.5)                            ==>  4.0  ; inexact

(round 7/2)                            ==>  4    ; exact
(round 7)                              ==>  7

(floor 1/0)                            ==>  1/0
(ceiling -1/0)                         ==>  -1/0
(truncate 0/0)                         ==>  0/0
(round 0/0)                            ==>  0/0

library procedure: rationalize x y

`Rationalize' returns the simplest rational number differing from x by no more than y. A rational number r_1 is simpler than another rational number r_2 if r_1 = p_1/q_1 and r_2 = p_2/q_2 (in lowest terms) and |p_1|<= |p_2| and |q_1| <= |q_2|. 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.

(rationalize
  (inexact->exact .3) 1/10)            ==> 1/3    ; exact
(rationalize .3 1/10)                  ==> #i1/3  ; inexact

(rationalize 1/0 3)                    ==>  1/0
(rationalize 1/0 1/0)                  ==>  0/0
(rationalize 3 1/0)                    ==>  0

procedure: exp z
procedure: log z
procedure: sin z
procedure: cos z
procedure: tan z
procedure: asin z
procedure: acos z
procedure: atan z
procedure: atan y x

These procedures are part of every implementation that supports general real numbers; they compute the usual transcendental functions. `Log' computes the natural logarithm of z (not the base ten logarithm). `Asin', `acos', and `atan' compute arcsine (sin-1), arccosine (cos-1), and arctangent (tan-1), respectively. The two-argument variant of `atan' computes (angle (make-rectangular x y)) (see below), even in implementations that don't support general complex numbers.

In general, the mathematical functions log, arcsine, arccosine, and arctangent are multiply defined. The value of log z is defined to be the one whose imaginary part lies in the range from -pi (exclusive) to pi (inclusive). log 0 is undefined. With log defined this way, the values of sin-1 z, cos-1 z, and tan-1 z are according to the following formulae:

sin-1 z = -i log (i z + sqrt(1 - z2))

cos-1 z = pi / 2 - sin-1 z

tan-1 z = (log (1 + i z) - log (1 - i z)) / (2 i)

The above specification follows [CLtL], which in turn cites [Penfield81]; refer to these sources for more detailed discussion of branch cuts, boundary conditions, and implementation of these functions. When it is possible these procedures produce a real result from a real argument.

If the function has a real-valued limit as its argument tends toward positive infinity, then that is the value returned by the function applied to 1/0. If the function has a real-valued limit as its argument tends toward negative infinity, then that is the value returned by the function applied to -1/0.

(exp 1/0)                   ==> 1/0
(exp -1/0)                  ==> 0.0
(log 1/0)                   ==> 1/0
(log 0.0)                   ==> -1/0
(log -1/0)                  ==> 0/0
(atan -1/0)                 ==> -1.5707963267948965
(atan 1/0)                  ==> 1.5707963267948965
The functions sin, cos, tan, asin, and acos either return 0/0 or report a violation of an implementation restriction when given 1/0, -1/0, or 0/0 as an argument.

procedure: sqrt z

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

(sqrt -5)                   ==>  0.0+2.23606797749979i
(sqrt 1/0)                  ==>  1/0
(sqrt -1/0)                 ==>  0/0

procedure: expt z1 z2

Returns z1 raised to the power z2. For z_1 ~= 0 inexact arguments

z_1^z_2 = e^z_2 log z_1

(define (expt z1 z2) (exp (* (if (zero? z1) (real-part z2) z2) (log z1))))

0^z is 1 if z = 0 and 0 otherwise. (expt 0.0 z) is 0.0 for z (including 1/0) having positive real part; is 1/0 for z (including -1/0) having negative real part; and is 0/0 or reports a violation of an implementation restriction for z having zero real part.

(expt 5 3)                  ==>  125
(expt 5 -3)                 ==>  8.0e-3
(expt 5 0)                  ==>  1
(expt 0 5)                  ==>  0
(expt 0 5+.0000312i)        ==>  0
(expt 0 -5)                 ==>  1/0
(expt 0 -5+.0000312i)       ==>  1/0
(expt 0 0)                  ==>  0/0

procedure: make-rectangular x1 x2
procedure: make-polar x3 x4
procedure: real-part z
procedure: imag-part z
procedure: magnitude z
procedure: angle z

These procedures are part of every implementation that supports general complex numbers. Suppose x1, x2, x3, and x4 are real numbers and z is a complex number such that

z = x1 + i x2 = x3 ei x4

Then

(make-rectangular x1 x2)               ==> z
(make-polar x3 x4)                     ==> z
(real-part z)                          ==> x1
(imag-part z)                          ==> x2
(magnitude z)                          ==> |x3|
(angle z)                              ==> x_angle

where -pi < x_angle <= pi with x_angle = x4 + 2pi n for some integer n.

(angle 1/0)                 ==> 0.0
(angle -1/0)                ==> 3.141592653589793

Rationale: `Magnitude' is the same as abs for a real argument, but `abs' must be present in all implementations, whereas `magnitude' need only be present in implementations that support general complex numbers.

procedure: exact->inexact z
procedure: inexact->exact z

`Exact->inexact' returns an inexact representation of z. The value returned is the inexact number that is numerically closest to the argument. If an exact argument has no reasonably close inexact equivalent, then a violation of an implementation restriction may be reported.

`Inexact->exact' returns an exact representation of z. The value returned is the exact number that is numerically closest to the argument. If an inexact argument has no reasonably close exact equivalent, 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. See section 6.2.3 Implementation restrictions.

`Exact->inexact' and `inexact->exact' are idempotent.

6.2.6 Numerical input and output

procedure: number->string z
procedure: number->string z radix

Radix must be an exact integer, either 2, 8, 10, or 16. If omitted, radix defaults to 10. The procedure `number->string' takes a number and a radix and returns as a string an external representation of the given number in the given radix such that

(let ((number number)
      (radix radix))
  (eqv? number
        (string->number (number->string number
                                        radix)
                        radix)))

is true. It is an error if no possible result makes this expression true.

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 [howtoprint], [howtoread]; otherwise the format of the result is unspecified.

The result returned by `number->string' never contains an explicit radix prefix.

Note: 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.

Rationale: If z is an inexact number represented using flonums, 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 non-flonum representations.

procedure: string->number string
procedure: string->number string radix

Returns a number of the maximally precise representation expressed by the given string. Radix must be an exact integer, either 2, 8, 10, or 16. If supplied, radix is a default radix that may be overridden by an explicit radix prefix in string (e.g. "#o177"). If radix is not supplied, then the default radix is 10. If string is not a syntactically valid notation for a number, then `string->number' returns #f.

(string->number "100")                 ==>  100
(string->number "100" 16)              ==>  256
(string->number "1e2")                 ==>  100.0
(string->number "15##")                ==>  1500.0
(string->number "1/0")                 ==>  1/0
(string->number "-1/0")                ==>  -1/0

Note: The domain of `string->number' may be restricted by implementations in the following ways. `String->number' is permitted to return #f whenever string contains an explicit radix prefix. If all numbers supported by an implementation are real, then `string->number' is permitted to return #f whenever string uses the polar or rectangular notations for complex numbers. If all numbers are integers, then `string->number' may return #f whenever the fractional notation is used. If all numbers are exact, then `string->number' may return #f whenever an exponent marker or explicit exactness prefix is used, or if a # appears in place of a digit. If all inexact numbers are integers, then `string->number' may return #f whenever a decimal point is used. An implementation may return #f for "0/0".

Implementation

Most of the glibc transcendental functions do the right things when passed IEEE-754 infinities. Code which integrates glibc functions into Scheme procedures handling complex numbers can be found in scm/Transcen.scm.

Here is code for the procedures extended from R5RS:

(define (finite? z)
  (not (and (= z (* 2 z)) (not (zero? z)))))

(define (ipow-by-squaring x n acc proc)
  (cond ((zero? n) acc)
	((eqv? 1 n) (proc acc x))
	(else (ipow-by-squaring (proc x x)
				(quotient n 2)
				(if (even? n) acc (proc acc x))
				proc))))

(define (integer-expt x n) (ipow-by-squaring x n 1 *))

(define (expt z1 z2)
  (if (and (exact? z2) (positive? z2))
      (integer-expt z1 z2)
      (exp (* (if (zero? z1) (real-part z2) z2) (log z1)))))

(define integer-quotient quotient)
(define integer-remainder remainder)
(define integer-modulo modulo)

(define (quotient x1 x2)
  (if (and (integer? x1) (integer? x2))
      (integer-quotient x1 x2)
      (truncate (/ x1 x2))))

(define (remainder x1 x2)
  (if (and (integer? x1) (integer? x2))
      (integer-remainder x1 x2)
      (- x1 (* x2 (quotient x1 x2)))))

(define (modulo x1 x2)
  (if (and (integer? x1) (integer? x2))
      (integer-modulo x1 x2)
      (- x1 (* x2 (floor (/ x1 x2))))))

(define integer-lcm lcm)
(define integer-gcd gcd)

(define (lcm . args)
  (/ (apply integer-lcm (map numerator args))
     (apply integer-gcd (map denominator args))))

(define (gcd . args)
  (/ (apply integer-gcd (map numerator args))
     (apply integer-lcm (map denominator args))))

(define almost-zero
  (do ((inc 1 (/ inc 2)) (linc 2 inc))
      ((zero? inc) linc)))

(define almost-inc #f)
(define almost-inf #f)
(do ((x 1.0 (+ x x))
     (x-prev 0.0 x))
    ((= x 1/0)
     (do ((x x-prev (+ x frac))
	  (frac (/ x-prev 2) (/ frac 2)))
	 ((= x 1/0))
       (set! almost-inc (* 2 frac))
       (set! almost-inf x))))

(define (series->limit proc series)
  (define val (proc (cadr series)))
  (define lval (proc (car series)))
  (define delta #f)
  (define ldelta #f)
  (define (loop series trend)
    (cond ;; don't PROC last X if diverging or there is no trend
     ((and (null? (cdr series)) (not trend) (zero? delta)) val)
     ((and (null? (cdr series)) (eq? trend 'diverging))
      (and (real? val) (if (negative? val) -1/0 1/0)))
     (else
      (set! ldelta delta)
      (set! lval val)
      (set! val (proc (car series)))
      (cond ((finite? val)
	     (set! delta (magnitude (- val lval)))
	     (case trend
	       ((converging)
		(cond ((null? (cdr series)) val)
		      ((> delta (+ almost-zero ldelta)) #f)
		      (else (loop (cdr series) trend))))
	       ((diverging)
		(cond ((< delta ldelta) #f)
		      ((null? (cdr series)) val)
		      (else (loop (cdr series) trend))))
	       (else
		(cond ((> delta (+ almost-zero ldelta))
		       (loop (cdr series) 'diverging))
		      ((< delta ldelta)
		       (loop (cdr series) 'converging))
		      (else
		       (loop (cdr series) trend))))))
	    (else val)))))
  (cond ((and (finite? val) (finite? lval))
	 (set! delta (magnitude (- val lval)))
	 (loop (cddr series) #f))
	((finite? lval) val)
	(else lval)))

(define (limit proc z1 . z2)
  (cond ((finite? z1)
	 (set! z2 (car z2))
	 (if (= z1 (+ z1 z2))
	     (proc z1)
	     (do ((x (+ z1 z2) (+ z1 dir))
		  (lst '() (cons x lst))
		  (dir (/ z2 4) (/ dir 4)))
		 ((= x z1)
		  (series->limit proc (reverse (cons x lst)))))))
	(else
	 (let ((aif ((if (negative? z1) - identity) almost-inf))
	       (ain ((if (negative? z1) - identity) almost-inc)))
	   (do ((x (+ aif (* -9 ain)) (+ x ain))
		(lst '() (cons x lst)))
	       ((not (finite? x))
		(series->limit proc (reverse (cons x lst)))))))))

Copyright

Copyright (C) Aubrey Jaffer 2005. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Editor: Mike Sperber
Last modified: Sun May 15 15:05:44 CEST 2005