Numbers
*******

XEmacs supports two to five numeric data types.  Integers and floating point numbers are always supported.  As a build-time option, bignums, ratios, and bigfloats may be enabled on some platforms.

Integers, which are what Common Lisp calls fixnums, are whole numbers such as -3, 0, #b0111, #xFEED, #o744.  Their values are exact, and their range is limited.  The number prefixes `#b', `#o', and `#x' are supported to represent numbers in binary, octal, and hexadecimal notation (or radix).  Floating point numbers are numbers with fractional parts, such as -4.5, 0.0, or 2.71828.  They can also be expressed in exponential notation: 1.5e2 equals 150; in this example, e2 stands for ten to the second power, and is multiplied by 1.5.  Floating point values are not exact; they have a fixed, limited amount of precision.

Bignums are arbitrary precision integers.  When supported, XEmacs can handle any integral calculations you have enough virtual memory to store.  (More precisely, on current architectures the representation allows integers whose storage would exhaust the address space.)  They are notated in the same way as other integers (fixnums).  XEmacs automatically converts results of computations from fixnum to bignum, and back, depending on the storage required to represent the number. Thus use of bignums are entirely transparent to the user, except for a few special applications that expect overflows.  Ratios are rational numbers with arbitrary precision.  (In theory fixed-size rationals could be supported, but for almost all applications floats are a reasonable substitute for fixed-precision rationals.)  They are notated in the usual way with the solidus, for example 5/3 or -22/7.  Bigfloats are floating point numbers with arbitrary precision.  Unlike integers, which are always infinitely precise if they can be represented, floating point numbers are inherently imprecise.  Therefore XEmacs automatically converts from float to bigfloat when floats and bigfloats are mixed in an expression, but a bigfloat will never be converted to a float unless the user explicitly coerces the value.  Nor will the result of a float operation be converted to bigfloat, except for ``contagion'' from another operand that is already a bigfloat.

Note that the term ``integer'' is used throughout the XEmacs documentation and code to mean ``fixnum''.  This is inconsistent with Common Lisp, and likely to cause confusion.  Similarly, ``float'' is used to mean ``fixed precision floating point number'', and the Common Lisp distinctions among short-floats, long-floats, and bigfloats are not reflected in XEmacs terminology.

Integer Basics
==============

The range of values for an integer depends on the machine.    If a multiple-precision arithmetic library is available on your platform, support for bignums, that is, integers with arbitrary precision, maybe compiled in to your XEmacs.  The rest of this section assumes that the bignum extension is not available.  The bignum extension and the user-visible differences in normal integer arithmetic are discussed in a separate section The Bignum Extension.

The minimum range is -1073741824 to 1073741823 (31 bits; i.e., -2**30 to 2**30 - 1), but some machines may provide a wider range.  Many examples in this chapter assume an integer has 31 bits.

The range of fixnums is available to Lisp programs:

 -- Variable: most-positive-fixnum
     The fixed-precision integer closest in value to positive infinity.

 -- Variable: most-negative-fixnum
     The fixed-precision integer closest in value to negative infinity.

Here is a common idiom to temporarily suppress garbage collection:

     (garbage-collect)
     (let ((gc-cons-threshold most-positive-fixnum))
       ;; allocation-intensive computation
       )
     (garbage-collect)

The Lisp reader reads an integer as a sequence of digits with optional initial sign and optional final period.

      1               ; The integer 1.
      1.              ; The integer 1.
     +1               ; Also the integer 1.
     -1               ; The integer -1.
      2147483648      ; Read error, due to overflow.
      0               ; The integer 0.
     -0               ; The integer 0.

To understand how various functions work on integers, especially the bitwise operators (see Bitwise Operations), it is often helpful to view the numbers in their binary form.

In 31-bit binary, the decimal integer 5 looks like this:

     000 0000  0000 0000  0000 0000  0000 0101

(We have inserted spaces between groups of 4 bits, and two spaces between groups of 8 bits, to make the binary integer easier to read.)

The integer -1 looks like this:

     111 1111  1111 1111  1111 1111  1111 1111

-1 is represented as 31 ones.  (This is called two's complement notation.)

The negative integer, -5, is creating by subtracting 4 from -1.  In binary, the decimal integer 4 is 100.  Consequently, -5 looks like this:

     111 1111  1111 1111  1111 1111  1111 1011

In this implementation, the largest 31-bit binary integer is the decimal integer 1,073,741,823.  In binary, it looks like this:

     011 1111  1111 1111  1111 1111  1111 1111

Since the arithmetic functions do not check whether integers go outside their range, when you add 1 to 1,073,741,823, the value is the negative integer -1,073,741,824:

     (+ 1 1073741823)
          => -1073741824
          => 100 0000  0000 0000  0000 0000  0000 0000

Many of the arithmetic functions accept markers for arguments as well as integers.  (see Markers.)  More precisely, the actual arguments to such functions may be either integers or markers, which is why we often give these arguments the name INT-OR-MARKER.  When the argument value is a marker, its position value is used and its buffer is ignored.

Ratio Basics
============

Ratios (built-in rational numbers) are available only when the bignum extension is built into your XEmacs.  This facility is new and experimental.  It is discussed in a separate section for convenience of updating the documentation The Bignum Extension.

Floating Point Basics
=====================

XEmacs supports floating point numbers.  The precise range of floating point numbers is machine-specific; it is the same as the range of the C data type double on the machine in question.  If a multiple-precision arithmetic library is available on your platform, support for bigfloats, that is, floating point numbers with arbitrary precision, maybe compiled in to your XEmacs.  The rest of this section assumes that the bignum extension is not available.  The bigfloat extension and the user-visible differences in normal float arithmetic are discussed in a separate section The Bignum Extension.

The printed representation for floating point numbers requires either a decimal point (with at least one digit following), an exponent, or both.  For example, 1500.0, 15e2, 15.0e2, 1.5e3, and .15e4 are five ways of writing a floating point number whose value is 1500.  They are all equivalent.  You can also use a minus sign to write negative floating point numbers, as in -1.0.

Most modern computers support the IEEE floating point standard, which provides for positive infinity and negative infinity as floating point values.  It also provides for a class of values called NaN or ``not-a-number''; numerical functions return such values in cases where there is no correct answer.  For example, (sqrt -1.0) returns a NaN.  For practical purposes, there's no significant difference between different NaN values in XEmacs Lisp, and there's no rule for precisely which NaN value should be used in a particular case, so this manual doesn't try to distinguish them.  XEmacs Lisp has no read syntax for NaNs or infinities; perhaps we should create a syntax in the future.

You can use logb to extract the binary exponent of a floating point number (or estimate the logarithm of an integer):

 -- Function: logb number
     This function returns the binary exponent of NUMBER.  More precisely, the value is the logarithm of NUMBER base 2, rounded down to an integer.

The range of floats is available to Lisp programs:

 -- Variable: most-positive-float
     The fixed-precision floating-point-number closest in value to positive infinity.

 -- Variable: most-negative-float
     The fixed-precision floating point number closest in value to negative infinity.

 -- Variable: least-positive-float
     The positive float closest in value to 0.  May not be normalized.

 -- Variable: least-negative-float
     The positive float closest in value to 0.  Must be normalized.

 -- Variable: least-positive-normalized-float
     The negative float closest in value to 0.  May not be normalized.

 -- Variable: least-negative-normalized-float
     The negative float closest in value to 0.  Must be normalized.

Note that for floating point numbers there is an interesting limit on how small they can get, as well as a limit on how big they can get.  In some representations, a floating point number is normalized if the leading digit is non-zero.  This allows representing numbers smaller than the most-negative exponent can express, by having fractional mantissas.  This means that the number is less precise than a normalized floating point number, so Lisp programs can detect loss of precision due to unnormalized floats by checking whether the number is between least-positive-float and least-positive-normalized-float.

The Bignum Extension
====================

In XEmacs 21.5.18, an extension was added by Jerry James to allow linking with arbitrary-precision arithmetic libraries if they are available on your platform.  ``Arbitrary'' precision means precisely what it says.  Your ability to work with large numbers is limited only by the amount of virtual memory (and time) you can throw at them.

As of 09 April 2004, support for the GNU Multiple Precision arithmetic library (GMP) is nearly complete, and support for the BSD Multiple Precision arithmetic library (MP) is being debugged.  To enable bignum support using GMP (respectively MP), invoke configure with your usual options, and add --use-number-lib=gmp (respectively --use-number-lib=mp).  The default is to disable bignum support, but if you are using a script to automate the build process, it may be convenient to explicitly disable support by appending --use-number-lib=no to your invocation of configure.  GMP has an MP compatibility mode, but it is not recommended, as there remain poorly understood bugs (even more so than for other vendors' versions of MP).

With GMP, exact arithmetic with integers and ratios of arbitrary precision and approximate (``floating point'') arithmetic of arbitrary precision are implemented efficiently in the library.  (Note that numerical implementations are quite delicate and sensitive to optimization.  If the library was poorly optimized for your hardware, as is often the case with Linux distributions for 80x86, you may achieve gains of several orders of magnitude by rebuilding the MP library.  See http://www.swox.com/gmp/gmp-speed.html.)  The MP implementation provides arbitrary precision integers, but ratios were implemented by the XEmacs implementer, Jerry James, who is not a numerical analyst.  Arbitrary precision floats are not available with MP.

The XEmacs bignum facility implements the Common Lisp notion of contagion, so that integers are always represented using the ``smallest'' representation that is exact, and integral ratios are converted to integers.  Since floating point arithmetic is inherently imprecise, numbers are implicitly coerced to bigfloats only if other operands in the expression are bigfloat, and bigfloats are only coerced to other numerical types by explicit calls to the function coerce.

Bignum support is incomplete.  If you would like to help with bignum support, especially on BSD MP, please subscribe to the XEmacs Beta mailing list (http://www.xemacs.org/Lists/#xemacs-beta), and book up on number-gmp.h and number-mp.h.  Jerry has promised to write internals documentation eventually, but if your skills run more to analysis and documentation than to writing new code, feel free to fill in the gap!

Bignum Basics
-------------

In most cases, bignum support should be transparent to users and Lisp programmers.  A bignum-enabled XEmacs will automatically convert from fixnums to bignums and back in pure integer arithmetic, and for GNU MP, from floats to bigfloats.  (Bigfloats must be explicitly coerced to other types, even if they are exactly representable by less precise types.)  The Lisp reader and printer have been enhanced to handle bignums, as have the mathematical functions.  Rationals (fixnums, bignums, and ratios) are printed using the %d, %o, %x, and %u format conversions.

Ratio Basics
------------

Ratios, when available have the read syntax and print representation 3/5.  Like other rationals (fixnums and bignums), they are printed using the %d, %o, %x, and %u format conversions.

Bigfloat Basics
---------------

Bigfloats, when available, have the same read syntax and print representations as fixed-precision floats.

Contagion
---------

Contagion is one way to address the requirement that an arithmetic operation should not fail because of differing types of the operands, or insufficient precision in the representation.  With bignum support, we can represent (+ most-positive-fixnum most-positive-fixnum) (or (* most-positive-fixnum most-positive-fixnum), for that matter) exactly.  There should be no overflow or ``wrap-around,'' and the computation should not be interrupted by an error.  Contagion is the idea that less precise operands are converted to the more precise type, and then the operation is performed.  This involves no loss of information, and therefore it is safe to do it automatically.

In XEmacs, the following rules of contagion are used:

 1. If a fixnum operation would overflow or underflow, the operands are promoted to bignums and the operation is performed.

 2. If a fixnum and a bignum are the operands, the fixnum is promoted to bignum, and the operation is performed.

 3. If a float operation would overflow or underflow (i.e., produce an unrepresentably small but non-zero result), the operands are converted to bigfloats and the operation performed.

 4. If an expression mixes a rational type (fixnum, bignum, or ratio) with a float, the rational operand is converted to a float and the operation performed if the result would fit in a float, otherwise both operands are promoted to bigfloat, and the operation performed.

 5. If an expression mixes any other type with a bigfloat, the other operand is converted to bigfloat and the operation performed.

Note that there is no contagion with ratios.  Integer-to-integer arithmetic with truncation or rounding is useful, and familiar. Therefore instead of converting the result of / to ratio if it is non-integral, the traditional definition is maintained, and a new function div is provided to give a ratio result if a division does not come out evenly.

On the other hand, the representation of arbitrary precision numbers is inefficient in both space and time.  The principle of canonicalization addresses this issue.  The idea of canonicalization is that when no information is lost, the representation should be demoted to the more efficient (smaller) representation.  Note that the inefficiency is likely to be greater than you might think. Experience with numerical analysis shows that in very precise calculations, precision tends to increase.  Thus it is typically wasted effort to attempt to convert to smaller representations, as the number is often reused and requires a larger representation.  However, XEmacs Lisp presumes that calculations using bignums are the exception, so it applies canonicalization.  The rules are

 1. If a ratio is integral, demote it to a bignum.  (In XEmacs Lisp all ratios are arbitrary precision numbers.)

 2. If a bignum is small enough to fit in a fixnum, demote it to fixnum.

Note that there are no rules to canonicalize floats or bigfloats.  This might seem surprising, but in both cases information will be lost.  Any floating point representation is implicitly approximate.  A conversion to a rational type, even if it seems exact, loses this information. More subtly, demoting a bigfloat to a smaller bigfloat or to a float would lose information about the precision of the result, and thus some information about the accuracy.  Thus floating point numbers are always already in canonical form.

Of course the programmer can explicitly request canonicalization, or more coercion to another type.  Coercion uses the Common Lisp compatibility function coerce from the cl-extra.el library.  A number can be explicitly converted to canonical form according to the above rules using

 -- Function: canonicalize-number number
     Return the canonical form of NUMBER.

Compatibility Issues
--------------------

Surgeon General's Warning: The automatic conversions cannot be disabled at runtime.  Old functions will not produce ratios unless there is a ratio operand, so there should be few surprises with type conflicts (the contagion rules are quite natural for Lisp programmers used to the behavior of integers and floats in pre-21.5.18 XEmacsen), but they can't be ruled out.  Also, if you work with extremely large numbers, your machine may arbitrarily decide to hand you an unpleasant surprise rather than a bignum.

User-visible changes in behavior include (in probable order of annoyance)

  * Arithmetic can cause a segfault, depending on your MP library.

     GMP by default allocates temporaries on the stack.  If you run out of stack space, you're dead; there is no way that we know of to reliably detect this condition, because alloca is typically implemented to be fast rather than robust.  If you just need a little more oomph, use a bigger stack (e.g., the ulimit -s command in bash(1)).  If you want robustness at the cost of speed, configure GMP with --disable-alloca and rebuild the GMP library.

     We do not know whether BSD MP uses alloca or not.  Please send any information you have as a bug report (M-x report-xemacs-bug RET), which will give us platform information.  (We do know that BSD MP implementations vary across vendors, but how much, we do not know yet.)

  * Terminology is not Common-Lisp-conforming.  For example, ``integer'' for Emacs Lisp means what Common Lisp calls ``fixnum''.  This issue is being investigated, but the use of ``integer'' for fixnum is pervasive and may cause backward-compatibility and GNU-Emacs-compatibility problems. There are similar issues for floating point numbers.  Since Emacs Lisp has not had a ratio type before, there should be no problems there.

  * An atom with ratio read syntax now returns a number, not a symbol.

  * Many operations that used to cause a range error now succeed, with intermediate results and return values coerced to bignums as needed.

  * The %u format conversion will now give an error if its argument is negative.  (Without MP, it prints a number which Lisp can't read.)

This is not a compatibility issue in the sense of specification, but careless programmers who have taken advantage of the immediate representation for numbers and written (eq x y) are in for a surprise.  This doesn't work with bignums, even if both arguments are bignums!  Arbitrary precision obviously requires consing new objects because the objects are ``large'' and of variable size, and the definition of eq does not permit different objects to compare as equal.  Instead of eq, use eql, in which numbers of the same type which have equal values compare equal, or =, which does any necessary type coercions before comparing for equality Comparison of Numbers.

Type Predicates for Numbers
===========================

The functions in this section test whether the argument is a number or whether it is a certain sort of number.  The functions integerp and floatp can take any type of Lisp object as argument (the predicates would not be of much use otherwise); but the zerop predicate requires a number as its argument.  See also integer-or-marker-p, integer-char-or-marker-p, number-or-marker-p and number-char-or-marker-p, in Predicates on Markers.

 -- Function: floatp object
     This predicate tests whether its argument is a floating point number and returns t if so, nil otherwise.

     floatp does not exist in Emacs versions 18 and earlier.

 -- Function: integerp object
     This predicate tests whether its argument is an integer, and returns t if so, nil otherwise.

 -- Function: numberp object
     This predicate tests whether its argument is a number (either integer or floating point), and returns t if so, nil otherwise.

 -- Function: natnump object
     The natnump predicate (whose name comes from the phrase ``natural-number-p'') tests to see whether its argument is a nonnegative integer, and returns t if so, nil otherwise.  0 is considered non-negative.

 -- Function: zerop number
     This predicate tests whether its argument is zero, and returns t if so, nil otherwise.  The argument must be a number.

     These two forms are equivalent: (zerop x) == (= x 0).

Comparison of Numbers
=====================

To test numbers for numerical equality, you should normally use =, not eq.  There can be many distinct floating point number objects with the same numeric value.  If you use eq to compare them, then you test whether two values are the same object.  By contrast, = compares only the numeric values of the objects.

In versions before 21.5.18, each integer value had a unique Lisp object in XEmacs Lisp.  Therefore, eq was equivalent to = where integers are concerned.  Even with the introduction of bignums, it is sometimes convenient to use eq for comparing an unknown value with an integer, because eq does not report an error if the unknown value is not a number---it accepts arguments of any type.  By contrast, = signals an error if the arguments are not numbers or markers.  However, it is a good idea to use = if you can, even for comparing exact values, because two bignums or ratios with the same value will often not be the same object.

There is another wrinkle: because floating point arithmetic is not exact, it is often a bad idea to check for equality of two floating point values.  Usually it is better to test for approximate equality. Here's a function to do this:

     (defconst fuzz-factor 1.0e-6)
     (defun approx-equal (x y)
       (or (and (= x 0) (= y 0))
           (< (/ (abs (- x y))
                 (max (abs x) (abs y)))
              fuzz-factor)))

     Common Lisp note: Comparing numbers in Common Lisp always requires = because Common Lisp implements multi-word integers, and two distinct integer objects can have the same numeric value.  XEmacs Lisp can have just one integer object for any given value because it has a limited range of integer values.

In addition to numbers, all of the following functions also accept characters and markers as arguments, and treat them as their number equivalents.

 -- Function: = number &rest more-numbers
     This function returns t if all of its arguments are numerically equal, nil otherwise.

          (= 5)
               => t
          (= 5 6)
               => nil
          (= 5 5.0)
               => t
          (= 5 5 6)
               => nil

 -- Function: /= number &rest more-numbers
     This function returns t if no two arguments are numerically equal, nil otherwise.

          (/= 5 6)
               => t
          (/= 5 5 6)
               => nil
          (/= 5 6 1)
               => t

 -- Function: < number &rest more-numbers
     This function returns t if the sequence of its arguments is monotonically increasing, nil otherwise.

          (< 5 6)
               => t
          (< 5 6 6)
               => nil
          (< 5 6 7)
               => t

 -- Function: <= number &rest more-numbers
     This function returns t if the sequence of its arguments is monotonically nondecreasing, nil otherwise.

          (<= 5 6)
               => t
          (<= 5 6 6)
               => t
          (<= 5 6 5)
               => nil

 -- Function: > number &rest more-numbers
     This function returns t if the sequence of its arguments is monotonically decreasing, nil otherwise.

 -- Function: >= number &rest more-numbers
     This function returns t if the sequence of its arguments is monotonically nonincreasing, nil otherwise.

 -- Function: max number &rest more-numbers
     This function returns the largest of its arguments.

          (max 20)
               => 20
          (max 1 2.5)
               => 2.5
          (max 1 3 2.5)
               => 3

 -- Function: min number &rest more-numbers
     This function returns the smallest of its arguments.

          (min -4 1)
               => -4

Numeric Conversions
===================

To convert an integer to floating point, use the function float.

 -- Function: float number
     This returns NUMBER converted to floating point. If NUMBER is already a floating point number, float returns it unchanged.

There are four functions to convert floating point numbers to integers; they differ in how they round.  These functions accept integer arguments also, and return such arguments unchanged.

 -- Function: truncate number
     This returns NUMBER, converted to an integer by rounding towards zero.

 -- Function: floor number &optional divisor
     This returns NUMBER, converted to an integer by rounding downward (towards negative infinity).

     If DIVISOR is specified, NUMBER is divided by DIVISOR before the floor is taken; this is the division operation that corresponds to mod.  An arith-error results if DIVISOR is 0.

 -- Function: ceiling number
     This returns NUMBER, converted to an integer by rounding upward (towards positive infinity).

 -- Function: round number
     This returns NUMBER, converted to an integer by rounding towards the nearest integer.  Rounding a value equidistant between two integers may choose the integer closer to zero, or it may prefer an even integer, depending on your machine.

Arithmetic Operations
=====================

XEmacs Lisp provides the traditional four arithmetic operations: addition, subtraction, multiplication, and division.  Remainder and modulus functions supplement the division functions.  The functions to add or subtract 1 are provided because they are traditional in Lisp and commonly used.

All of these functions except % return a floating point value if any argument is floating.

It is important to note that in XEmacs Lisp, arithmetic functions do not check for overflow.  Thus (1+ 134217727) may evaluate to -134217728, depending on your hardware.

 -- Function: 1+ number
     This function returns NUMBER plus one.  NUMBER may be a number, character or marker.  Markers and characters are converted to integers.

     For example,

          (setq foo 4)
               => 4
          (1+ foo)
               => 5

     This function is not analogous to the C operator ++---it does not increment a variable.  It just computes a sum.  Thus, if we continue,

          foo
               => 4

     If you want to increment the variable, you must use setq, like this:

          (setq foo (1+ foo))
               => 5

     Now that the cl package is always available from lisp code, a more convenient and natural way to increment a variable is (incf foo).

 -- Function: 1- number
     This function returns NUMBER minus one.  NUMBER may be a number, character or marker.  Markers and characters are converted to integers.

 -- Function: abs number
     This returns the absolute value of NUMBER.

 -- Function: + &rest numbers
     This function adds its arguments together.  When given no arguments, + returns 0.

     If any of the arguments are characters or markers, they are first converted to integers.

          (+)
               => 0
          (+ 1)
               => 1
          (+ 1 2 3 4)
               => 10

 -- Function: - &optional number &rest other-numbers
     The - function serves two purposes: negation and subtraction. When - has a single argument, the value is the negative of the argument.  When there are multiple arguments, - subtracts each of the OTHER-NUMBERS from NUMBER, cumulatively.  If there are no arguments, an error is signaled.

     If any of the arguments are characters or markers, they are first converted to integers.

          (- 10 1 2 3 4)
               => 0
          (- 10)
               => -10
          (-)
               => 0

 -- Function: * &rest numbers
     This function multiplies its arguments together, and returns the product.  When given no arguments, * returns 1.

     If any of the arguments are characters or markers, they are first converted to integers.

          (*)
               => 1
          (* 1)
               => 1
          (* 1 2 3 4)
               => 24

 -- Function: / dividend &rest divisors
     The / function serves two purposes: inversion and division.  When / has a single argument, the value is the inverse of the argument.  When there are multiple arguments, / divides DIVIDEND by each of the DIVISORS, cumulatively, returning the quotient.  If there are no arguments, an error is signaled.

     If none of the arguments are floats, then the result is an integer. This means the result has to be rounded.  On most machines, the result is rounded towards zero after each division, but some machines may round differently with negative arguments.  This is because the Lisp function / is implemented using the C division operator, which also permits machine-dependent rounding.  As a practical matter, all known machines round in the standard fashion.

     If any of the arguments are characters or markers, they are first converted to integers.

     If you divide by 0, an arith-error error is signaled. (see Errors.)

          (/ 6 2)
               => 3

          (/ 5 2)
               => 2
          (/ 25 3 2)
               => 4
          (/ 3.0)
               => 0.3333333333333333
          (/ -17 6)
               => -2

     The result of (/ -17 6) could in principle be -3 on some machines.

 -- Function: % dividend divisor
     This function returns the integer remainder after division of DIVIDEND by DIVISOR.  The arguments must be integers or markers.

     For negative arguments, the remainder is in principle machine-dependent since the quotient is; but in practice, all known machines behave alike.

     An arith-error results if DIVISOR is 0.

          (% 9 4)
               => 1
          (% -9 4)
               => -1
          (% 9 -4)
               => 1
          (% -9 -4)
               => -1

     For any two integers DIVIDEND and DIVISOR,

          (+ (% DIVIDEND DIVISOR)
             (* (/ DIVIDEND DIVISOR) DIVISOR))

     always equals DIVIDEND.

 -- Function: mod dividend divisor
     This function returns the value of DIVIDEND modulo DIVISOR; in other words, the remainder after division of DIVIDEND by DIVISOR, but with the same sign as DIVISOR. The arguments must be numbers or markers.

     Unlike %, mod returns a well-defined result for negative arguments.  It also permits floating point arguments; it rounds the quotient downward (towards minus infinity) to an integer, and uses that quotient to compute the remainder.

     An arith-error results if DIVISOR is 0.

          (mod 9 4)
               => 1

          (mod -9 4)
               => 3

          (mod 9 -4)
               => -3

          (mod -9 -4)
               => -1

          (mod 5.5 2.5)
               => .5

     For any two numbers DIVIDEND and DIVISOR,

          (+ (mod DIVIDEND DIVISOR)
             (* (floor DIVIDEND DIVISOR) DIVISOR))

     always equals DIVIDEND, subject to rounding error if either argument is floating point.  For floor, see Numeric Conversions.

Rounding Operations
===================

The functions ffloor, fceiling, fround and ftruncate take a floating point argument and return a floating point result whose value is a nearby integer.  ffloor returns the nearest integer below; fceiling, the nearest integer above; ftruncate, the nearest integer in the direction towards zero; fround, the nearest integer.

 -- Function: ffloor number
     This function rounds NUMBER to the next lower integral value, and returns that value as a floating point number.

 -- Function: fceiling number
     This function rounds NUMBER to the next higher integral value, and returns that value as a floating point number.

 -- Function: ftruncate number
     This function rounds NUMBER towards zero to an integral value, and returns that value as a floating point number.

 -- Function: fround number
     This function rounds NUMBER to the nearest integral value, and returns that value as a floating point number.

Bitwise Operations on Integers
==============================

In a computer, an integer is represented as a binary number, a sequence of bits (digits which are either zero or one).  A bitwise operation acts on the individual bits of such a sequence.  For example, shifting moves the whole sequence left or right one or more places, reproducing the same pattern ``moved over''.

The bitwise operations in XEmacs Lisp apply only to integers.

 -- Function: lsh integer1 count
     lsh, which is an abbreviation for logical shift, shifts the bits in INTEGER1 to the left COUNT places, or to the right if COUNT is negative, bringing zeros into the vacated bits.  If COUNT is negative, lsh shifts zeros into the leftmost (most-significant) bit, producing a positive result even if INTEGER1 is negative.  Contrast this with ash, below.

     Here are two examples of lsh, shifting a pattern of bits one place to the left.  We show only the low-order eight bits of the binary pattern; the rest are all zero.

          (lsh 5 1)
               => 10
          ;; Decimal 5 becomes decimal 10.
          00000101 => 00001010

          (lsh 7 1)
               => 14
          ;; Decimal 7 becomes decimal 14.
          00000111 => 00001110

     As the examples illustrate, shifting the pattern of bits one place to the left produces a number that is twice the value of the previous number.

     Shifting a pattern of bits two places to the left produces results like this (with 8-bit binary numbers):

          (lsh 3 2)
               => 12
          ;; Decimal 3 becomes decimal 12.
          00000011 => 00001100

     On the other hand, shifting one place to the right looks like this:

          (lsh 6 -1)
               => 3
          ;; Decimal 6 becomes decimal 3.
          00000110 => 00000011

          (lsh 5 -1)
               => 2
          ;; Decimal 5 becomes decimal 2.
          00000101 => 00000010

     As the example illustrates, shifting one place to the right divides the value of a positive integer by two, rounding downward.

     The function lsh, like all XEmacs Lisp arithmetic functions, does not check for overflow, so shifting left can discard significant bits and change the sign of the number.  For example, left shifting 134,217,727 produces -2 on a 28-bit machine:

          (lsh 134217727 1)          ; left shift
               => -2

     In binary, in the 28-bit implementation, the argument looks like this:

          ;; Decimal 134,217,727
          0111  1111 1111  1111 1111  1111 1111

     which becomes the following when left shifted:

          ;; Decimal -2
          1111  1111 1111  1111 1111  1111 1110

 -- Function: ash integer1 count
     ash (arithmetic shift) shifts the bits in INTEGER1 to the left COUNT places, or to the right if COUNT is negative.

     ash gives the same results as lsh except when INTEGER1 and COUNT are both negative.  In that case, ash puts ones in the empty bit positions on the left, while lsh puts zeros in those bit positions.

     Thus, with ash, shifting the pattern of bits one place to the right looks like this:

          (ash -6 -1) => -3
          ;; Decimal -6 becomes decimal -3.
          1111  1111 1111  1111 1111  1111 1010
               =>
          1111  1111 1111  1111 1111  1111 1101

     In contrast, shifting the pattern of bits one place to the right with lsh looks like this:

          (lsh -6 -1) => 134217725
          ;; Decimal -6 becomes decimal 134,217,725.
          1111  1111 1111  1111 1111  1111 1010
               =>
          0111  1111 1111  1111 1111  1111 1101

     Here are other examples:

                             ;               28-bit binary values

          (lsh 5 2)          ;   5  =  0000  0000 0000  0000 0000  0000 0101
               => 20         ;      =  0000  0000 0000  0000 0000  0001 0100

          (ash 5 2)
               => 20
          (lsh -5 2)         ;  -5  =  1111  1111 1111  1111 1111  1111 1011
               => -20        ;      =  1111  1111 1111  1111 1111  1110 1100
          (ash -5 2)
               => -20

          (lsh 5 -2)         ;   5  =  0000  0000 0000  0000 0000  0000 0101
               => 1          ;      =  0000  0000 0000  0000 0000  0000 0001

          (ash 5 -2)
               => 1

          (lsh -5 -2)        ;  -5  =  1111  1111 1111  1111 1111  1111 1011
               => 4194302    ;      =  0011  1111 1111  1111 1111  1111 1110

          (ash -5 -2)        ;  -5  =  1111  1111 1111  1111 1111  1111 1011
               => -2         ;      =  1111  1111 1111  1111 1111  1111 1110

 -- Function: logand &rest ints-or-markers
     This function returns the ``logical and'' of the arguments: the Nth bit is set in the result if, and only if, the Nth bit is set in all the arguments.  (``Set'' means that the value of the bit is 1 rather than 0.)

     For example, using 4-bit binary numbers, the ``logical and'' of 13 and 12 is 12: 1101 combined with 1100 produces 1100. In both the binary numbers, the leftmost two bits are set (i.e., they are 1's), so the leftmost two bits of the returned value are set. However, for the rightmost two bits, each is zero in at least one of the arguments, so the rightmost two bits of the returned value are 0's.

     Therefore,

          (logand 13 12)
               => 12

     If logand is not passed any argument, it returns a value of -1.  This number is an identity element for logand because its binary representation consists entirely of ones.  If logand is passed just one argument, it returns that argument.

                             ;                28-bit binary values

          (logand 14 13)     ; 14  =  0000  0000 0000  0000 0000  0000 1110
                             ; 13  =  0000  0000 0000  0000 0000  0000 1101
               => 12         ; 12  =  0000  0000 0000  0000 0000  0000 1100

          (logand 14 13 4)   ; 14  =  0000  0000 0000  0000 0000  0000 1110
                             ; 13  =  0000  0000 0000  0000 0000  0000 1101
                             ;  4  =  0000  0000 0000  0000 0000  0000 0100
               => 4          ;  4  =  0000  0000 0000  0000 0000  0000 0100

          (logand)
               => -1         ; -1  =  1111  1111 1111  1111 1111  1111 1111

 -- Function: logior &rest ints-or-markers
     This function returns the ``inclusive or'' of its arguments: the Nth bit is set in the result if, and only if, the Nth bit is set in at least one of the arguments.  If there are no arguments, the result is zero, which is an identity element for this operation.  If logior is passed just one argument, it returns that argument.

                             ;               28-bit binary values

          (logior 12 5)      ; 12  =  0000  0000 0000  0000 0000  0000 1100
                             ;  5  =  0000  0000 0000  0000 0000  0000 0101
               => 13         ; 13  =  0000  0000 0000  0000 0000  0000 1101

          (logior 12 5 7)    ; 12  =  0000  0000 0000  0000 0000  0000 1100
                             ;  5  =  0000  0000 0000  0000 0000  0000 0101
                             ;  7  =  0000  0000 0000  0000 0000  0000 0111
               => 15         ; 15  =  0000  0000 0000  0000 0000  0000 1111

 -- Function: logxor &rest ints-or-markers
     This function returns the ``exclusive or'' of its arguments: the Nth bit is set in the result if, and only if, the Nth bit is set in an odd number of the arguments.  If there are no arguments, the result is 0, which is an identity element for this operation.  If logxor is passed just one argument, it returns that argument.

                             ;               28-bit binary values

          (logxor 12 5)      ; 12  =  0000  0000 0000  0000 0000  0000 1100
                             ;  5  =  0000  0000 0000  0000 0000  0000 0101
               => 9          ;  9  =  0000  0000 0000  0000 0000  0000 1001

          (logxor 12 5 7)    ; 12  =  0000  0000 0000  0000 0000  0000 1100
                             ;  5  =  0000  0000 0000  0000 0000  0000 0101
                             ;  7  =  0000  0000 0000  0000 0000  0000 0111
               => 14         ; 14  =  0000  0000 0000  0000 0000  0000 1110

 -- Function: lognot integer
     This function returns the logical complement of its argument: the Nth bit is one in the result if, and only if, the Nth bit is zero in INTEGER, and vice-versa.

          (lognot 5)
               => -6
          ;;  5  =  0000  0000 0000  0000 0000  0000 0101
          ;; becomes
          ;; -6  =  1111  1111 1111  1111 1111  1111 1010

Standard Mathematical Functions
===============================

These mathematical functions are available if floating point is supported (which is the normal state of affairs).  They allow integers as well as floating point numbers as arguments.

 -- Function: sin number
 -- Function: cos number
 -- Function: tan number
     These are the ordinary trigonometric functions, with argument measured in radians.

 -- Function: asin number
     The value of (asin NUMBER) is a number between -pi/2 and pi/2 (inclusive) whose sine is NUMBER; if, however, NUMBER is out of range (outside [-1, 1]), then the result is a NaN.

 -- Function: acos number
     The value of (acos NUMBER) is a number between 0 and pi (inclusive) whose cosine is NUMBER; if, however, NUMBER is out of range (outside [-1, 1]), then the result is a NaN.

 -- Function: atan number &optional number2
     The value of (atan NUMBER) is a number between -pi/2 and pi/2 (exclusive) whose tangent is NUMBER.

     If optional argument NUMBER2 is supplied, the function returns atan2(NUMBER,NUMBER2).

 -- Function: sinh number
 -- Function: cosh number
 -- Function: tanh number
     These are the ordinary hyperbolic trigonometric functions.

 -- Function: asinh number
 -- Function: acosh number
 -- Function: atanh number
     These are the inverse hyperbolic trigonometric functions.

 -- Function: exp number
     This is the exponential function; it returns e to the power NUMBER.  e is a fundamental mathematical constant also called the base of natural logarithms.

 -- Function: log number &optional base
     This function returns the logarithm of NUMBER, with base BASE. If you don't specify BASE, the base e is used.  If NUMBER is negative, the result is a NaN.

 -- Function: log10 number
     This function returns the logarithm of NUMBER, with base 10.  If NUMBER is negative, the result is a NaN.  (log10 X) == (log X 10), at least approximately.

 -- Function: expt x y
     This function returns X raised to power Y.  If both arguments are integers and Y is positive, the result is an integer; in this case, it is truncated to fit the range of possible integer values.

 -- Function: sqrt number
     This returns the square root of NUMBER.  If NUMBER is negative, the value is a NaN.

 -- Function: cube-root number
     This returns the cube root of NUMBER.

Random Numbers
==============

A deterministic computer program cannot generate true random numbers. For most purposes, pseudo-random numbers suffice.  A series of pseudo-random numbers is generated in a deterministic fashion.  The numbers are not truly random, but they have certain properties that mimic a random series.  For example, all possible values occur equally often in a pseudo-random series.

In XEmacs, pseudo-random numbers are generated from a ``seed'' number. Starting from any given seed, the random function always generates the same sequence of numbers.  XEmacs always starts with the same seed value, so the sequence of values of random is actually the same in each XEmacs run!  For example, in one operating system, the first call to (random) after you start XEmacs always returns -1457731, and the second one always returns -7692030.  This repeatability is helpful for debugging.

If you want truly unpredictable random numbers, execute (random t).  This chooses a new seed based on the current time of day and on XEmacs's process ID number.

 -- Function: random &optional limit
     This function returns a pseudo-random integer.  Repeated calls return a series of pseudo-random integers.

     If LIMIT is a positive integer, the value is chosen to be nonnegative and less than LIMIT.

     If LIMIT is t, it means to choose a new seed based on the current time of day and on XEmacs's process ID number.

     On some machines, any integer representable in Lisp may be the result of random.  On other machines, the result can never be larger than a certain maximum or less than a certain (negative) minimum.