@c -*-texinfo-*-
@c This is part of the XEmacs Lisp Reference Manual.
@c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
@c See the file lispref.texi for copying conditions.
@setfilename ../../info/numbers.info
@node Numbers, Strings and Characters, Lisp Data Types, Top
@chapter Numbers
@c #### Improve the indexing in this file!!!!
@cindex integers
@cindex numbers

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

  Fixnums (called just @dfn{integers} in GNU Emacs and older versions
of XEmacs) are whole numbers such as @minus{}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).  The syntax
`#NNNrNUM' is also supported, allowing a radix to be explicitly
specified; e.g. `#20r15' denotes the fixnum 25, expressed in base
twenty.

  Floating point numbers are numbers with fractional parts, such as
@minus{}4.5, 0.0, or 2.71828.  They can also be expressed in exponential
notation: 1.5e2 equals 150; in this example, @samp{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.  They are notated
in the usual way with the solidus, for example 5/3 or @minus{}22/7.  The
syntax for using a particular radix is the same as that for integers,
so, e.g., @samp{#x8/10} is equivalent to @samp{1/2} and @samp{#30r10/4}
to @samp{15/2}, respectively.

  Bigfloats are floating point numbers with arbitrary precision, which
may be specified by the user (and may be different for different
bigfloats at the same time).  Unlike integers, which are always
infinitely precise if they can be represented, floating point numbers
are inherently imprecise.  This means that choice of precision can be a
very delicate issue.  XEmacs automatically converts @emph{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.  However, when bigfloats of differing
precision are mixed, the result will always have the larger precision.
The exact rules are more carefully explained elsewhere
(@pxref{Canonicalization and Contagion}).

  Common Lisp terminology and historical Emacs terminology conflict
here, to an extent.  We attempt to use ``fixnum'' and ``integer''
consistently, but older XEmacs and GNU Emacs code and documentation use
the latter to mean the former.  ``Float'' is used in Emacs documentation
to mean ``fixed precision floating point number'', and the Common Lisp
distinctions among @dfn{short-floats}, @dfn{long-floats}, @emph{etc.},
and bigfloats (which are not standardized in Common Lisp) are not
reflected in XEmacs terminology.  We're working on this, but volunteers
to fix it in the XEmacs manuals would be heartily welcomed.

@menu
* Integer Basics::            Representation and range of integers.
* Rational Basics::           Representation and range of rational numbers.
* Float Basics::              Representation and range of floating point.
* The Bignum Extension::      Arbitrary precision integers, ratios, and floats.
* Predicates on Numbers::     Testing for numbers.
* Comparison of Numbers::     Equality and inequality predicates.
* Numeric Conversions::       Converting float to integer and vice versa.
* Arithmetic Operations::     How to add, subtract, multiply and divide.
* Rounding Operations::       Explicitly rounding floating point numbers.
* Bitwise Operations::        Logical and, or, not, shifting.
* Math Functions::            Trig, exponential and logarithmic functions.
* Random Numbers::            Obtaining random integers, predictable or not.
@end menu

@node Integer Basics, Rational Basics, Numbers, Numbers
@section 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, may be
compiled in to your XEmacs.  The rest of this section assumes that the
bignum extension is @emph{not} available.  The bignum extension and the
user-visible differences in normal integer arithmetic are discussed in a
separate section @ref{The Bignum Extension}.

The minimum range is @minus{}1073741824 to 1073741823 (31 bits; i.e.,
@ifinfo
-2**30
@end ifinfo
@tex
$-2^{30}$
@end tex
to
@ifinfo
2**30 - 1),
@end ifinfo
@tex
$2^{30}-1$),
@end tex
but some machines may provide a wider range.  Many examples in this
chapter assume an integer has 31 bits.
@cindex overflow

The range of fixnums is available to Lisp programs:

@defvar most-positive-fixnum
The fixed-precision integer closest in value to positive infinity.
@end defvar

@defvar most-negative-fixnum
The fixed-precision integer closest in value to negative infinity.
@end defvar

Here is a common idiom to temporarily suppress garbage collection:
@example
(garbage-collect)
(let ((gc-cons-threshold most-positive-fixnum))
  ;; allocation-intensive computation
  )
(garbage-collect)
@end example

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

@example
 1               ; @r{The integer 1.}
 1.              ; @r{The integer 1.}
+1               ; @r{Also the integer 1.}
-1               ; @r{The integer @minus{}1.}
 2147483648      ; @r{Read error, due to overflow.}
 0               ; @r{The integer 0.}
-0               ; @r{The integer 0.}
@end example

  To understand how various functions work on integers, especially the
bitwise operators (@pxref{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:

@example
000 0000  0000 0000  0000 0000  0000 0101
@end example

@noindent
(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 @minus{}1 looks like this:

@example
111 1111  1111 1111  1111 1111  1111 1111
@end example

@noindent
@cindex two's complement
@minus{}1 is represented as 31 ones.  (This is called @dfn{two's
complement} notation.)

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

@example
111 1111  1111 1111  1111 1111  1111 1011
@end example

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

@example
011 1111  1111 1111  1111 1111  1111 1111
@end example

  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 @minus{}1,073,741,824:

@example
(+ 1 1073741823)
     @result{} -1073741824
     @result{} 100 0000  0000 0000  0000 0000  0000 0000
@end example

  Many of the arithmetic functions accept markers for arguments as well
as integers.  (@xref{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 @var{int-or-marker}.  When the argument
value is a marker, its position value is used and its buffer is ignored.

@ignore
  In version 19, except where @emph{integer} is specified as an
argument, all of the functions for markers and integers also work for
floating point numbers.
@end ignore


@node Rational Basics, Float Basics, Integer Basics, Numbers
@section Rational 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 @ref{The Bignum Extension}.  The following
functions are defined regardless of the presence of the extension, but
have trivial results for integers.

@defun numerator rational
@cindex numbers
Return the numerator of the canonical form of @var{rational}.
If @var{rational} is an integer, @var{rational} is returned.
@var{rational} must be an integer or a ratio.
@end defun

@defun denominator rational
Return the denominator of the canonical form of @var{rational}.
If @var{rational} is an integer, 1 is returned.  @var{rational} must be
an integer or a ratio.
@end defun


@node Float Basics, The Bignum Extension, Rational Basics, Numbers
@section 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 @code{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, may be compiled in to your XEmacs.  The rest of this section
assumes that the bignum extension is @emph{not} available.  The bigfloat
extension and the user-visible differences in normal float arithmetic
are discussed in a separate section @ref{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, @samp{1500.0}, @samp{15e2}, @samp{15.0e2},
@samp{1.5e3}, and @samp{.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
@samp{-1.0}.

@cindex IEEE floating point
@cindex positive infinity
@cindex negative infinity
@cindex infinity
@cindex NaN
   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, @code{(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 @code{logb} to extract the binary exponent of a floating
point number (or estimate the logarithm of an integer):

@defun logb number
This function returns the binary exponent of @var{number}.  More
precisely, the value is the logarithm of @var{number} base 2, rounded
down to an integer.
@end defun

The range of floats is available to Lisp programs:

@defvar most-positive-float
The fixed-precision floating-point-number closest in value to positive
infinity.
@end defvar

@defvar most-negative-float
The fixed-precision floating point number closest in value to negative
infinity.
@end defvar

@defvar least-positive-float
The positive float closest in value to 0.  May not be normalized.
@end defvar

@defvar least-negative-float
The positive float closest in value to 0.  Must be normalized.
@end defvar

@defvar least-positive-normalized-float
The negative float closest in value to 0.  May not be normalized.
@end defvar

@defvar least-negative-normalized-float
The negative float closest in value to 0.  Must be normalized.
@end defvar

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 @dfn{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
@code{least-positive-float} and @code{least-positive-normalized-float}.


@node The Bignum Extension, Predicates on Numbers, Float Basics, Numbers
@section The Bignum Extension

  In XEmacs 21.5.18, an extension was added by @email{james@@xemacs.org,
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.

  XEmacs supports the GNU Multiple Precision arithmetic library (GMP),
the Multiple Precision Integers and Rationals library (MPIR), and the
BSD Multiple Precision arithmetic library (MP).  To enable bignum
support using GMP, MPIR, or MP, invoke configure with your usual options
and add @samp{--use-number-lib=gmp}, @samp{--use-number-lib=mpir}, or
@samp{--use-number-lib=mp}, respectively.  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
@emph{appending} @samp{--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 and MPIR, 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 @emph{several orders of magnitude} by rebuilding the MP
library.  See @uref{http://gmplib.org/gmpbench.html}.)  The MP
implementation provides arbitrary precision integers.  Ratios and
arbitrary precision floats are not available with MP.

  If your code needs to run correctly whether or not the feature is
provided, you may test for the features @code{bignum}, @code{ratio}, and
@code{bigfloat}.

  The XEmacs bignum facility implements the Common Lisp notions of
@dfn{canonicalization} and @dfn{contagion}.  Canonicalization means that
in exact (integer and ratio) arithmetic, a result of an operation is
always converted to the ``smallest'' type that can represent it
exactly.  For exact numbers, the user only cares if efficiency is
extremely important; Lisp does not try to determine an order of
computation that avoids conversion to bignum (or ratio) even if one is
available.  (Note that integers are never silently converted to
ratios: the result of @code{(/ 1 2)} is the integer @code{0}.  You can
@emph{request} that a ratio be used if needed with @code{(div 1 2)}.)

  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 @code{coerce}.

@menu
* Bignum Basics::             Representation and range of integers.
* Ratio Basics::              Representation and range of rational numbers.
* Bigfloat Basics::           Representation and range of floating point.
* Canonicalization and Contagion::  Automatic coercion to other types.
* Compatibility Issues::      Changes in fixed-precision arithmetic.
@end menu


@node Bignum Basics, Ratio Basics, The Bignum Extension, The Bignum Extension
@subsection 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 GMP and
MPIR, 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 @samp{%d}, @samp{%o},
@samp{%x}, and @samp{%u} format conversions.


@node Ratio Basics, Bigfloat Basics, Bignum Basics, The Bignum Extension
@subsection Ratio Basics

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


@node Bigfloat Basics, Canonicalization and Contagion, Ratio Basics, The Bignum Extension
@subsection Bigfloat Basics

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

It is possible to make bigfloat the default floating point format by
setting @code{default-float-precision} to a non-zero value.  Precision
is given in bits, with a maximum precision of
@code{bigfloat-maximum-precision}.

@example
(let* ((float1 (string-to-number "9999999999999999.99999999999999999999"))
       (default-float-precision 256)
       (float2 (string-to-number "9999999999999999.99999999999999999999")))
  (+ (if (bigfloatp float1) 1 0)
     (if (bigfloatp float2) 2 0)))
    @result{} 2
@end example

@example
(let* ((float1 (float 999999999999999999999999999999999999999999999999999999))
       (default-float-precision 256)
       (float2 (float 999999999999999999999999999999999999999999999999999999)))
  (princ float1)
  (terpri)
  (princ float2)
  (terpri))
    @result{} 9.999999999999999e+53
9.99999999999999999999999999999999999999999999999999999E53
t
@end example

Explicit type coercion is also available, although then the precision of
the bigfloat is no greater than the source type.

@example
(coerce 999999999999999 'bigfloat)
    @result{} 9.99999999999999E14
@end example

@node Canonicalization and Contagion, Compatibility Issues, Bigfloat Basics, The Bignum Extension
@subsection Canonicalization and Contagion

@dfn{Canonicalization} is a rule intended to enhance the time and space
efficiency of exact arithmetic.  Because bignums and ratios are
implemented as record objects, they take up much more space than
fixnums, which are implemented as an immediate object.  Conversions and
calls to the MP library also take time.  So the implementation always
converts the result of exact arithmetic to the smallest representation
that can exactly represent the quantity.

@example
(+ 3/4 5)
    @result{} 23/4

(+ 3/4 1/4 2)
    @result{} 3
@end example

Conversely, if an integer (read or computed) cannot be represented as a
fixnum, a bignum will be used.  Integer division is a somewhat
exceptional case.  Because it is useful and is the historical meaning of
the function @code{/}, a separate function @code{div} is provided.
@code{div} is identical to @code{/} except that when the rational result
is not an integer, it is represented exactly as a ratio.  In both cases
if a rational result is an integer, it is automatically converted to the
appropriate integral representation.

  Note that the efficiency gain from canonicalization is likely to be
less than you might think. Experience with numerical analysis shows that
in very precise calculations, the required 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.

@dfn{Contagion} is one way to address the requirement that an arithmetic
operation should not fail because of differing types of the operands.
Contagion is the idea that less precise operands are converted to the
more precise type, and then the operation is performed.  While changing
precision is a delicate issue, contagion is so useful that XEmacs
performs it automatically.

In XEmacs, the following rules of contagion are used:

@c #### this probably wants names for each rule
@enumerate
@item
If an expression mixes an integral type with a ratio, then the usual
rules of rational arithmetic apply.  (If the result of the expression
happens to be an integer, it will be canonicalized to integer.)

@item
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.

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

@item
If bigfloats of different precision are mixed, all are converted to the
@emph{highest} precision, and the operation performed.
@end enumerate

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 @code{coerce} from the @file{cl-extra.el}
library.  A number can be explicitly converted to canonical form
according to the above rules using

@defun canonicalize-number number
Return the canonical form of @var{number}.
@end defun

However, if we've done our job properly, this is always a no-op.  That
is, if you find a number in un-canonicalized form, please report it as a
bug.


@node Compatibility Issues,  , Canonicalization and Contagion, The Bignum Extension
@subsection Compatibility Issues

  @emph{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)

@itemize
@item
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 @samp{alloca} is typically implemented to
be @emph{fast} rather than robust.  If you just need a little more
oomph, use a bigger stack (@emph{e.g.}, the @file{ulimit -s} command in
bash(1)).  If you want robustness at the cost of speed, configure GMP
with @samp{--disable-alloca} and rebuild the GMP library.

We do not know whether BSD MP uses @samp{alloca} or not.  Please send
any information you have as a bug report (@kbd{M-x report-xemacs-bug
@key{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.)

@item
Our documentation's terminology, and our API terminology, is not always
Common-Lisp-conforming.  Many places use ``integer'' where ``fixnum''
better reflects what the code accepts or produces; there are similar
issues for the varying types of floating point numbers.  Since Emacs
Lisp has not had a ratio type before, there are no problems there.

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

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

@item
The @samp{%u} format conversion will now give an error if its argument
is negative.  (Without MP, it prints a number which Lisp can't read.)
@end itemize

  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 @code{(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 @samp{eq} does not permit different objects to compare as
equal.  Instead of @code{eq}, use @code{eql}, in which numbers of the
same type which have equal values compare equal, or @code{=}, which does
any necessary type coercions before comparing for equality
@ref{Comparison of Numbers}.


@node Predicates on Numbers, Comparison of Numbers, The Bignum Extension, Numbers
@section 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 which test for
type can take any type of Lisp object as argument (the more general
predicates would not be of much use otherwise).  However, the
@code{zerop} predicate requires a number as its argument, and the
@code{evenp}, and @code{oddp} predicates require integers as their
arguments.  See also @code{integer-or-marker-p},
@code{integer-char-or-marker-p}, @code{number-or-marker-p} and
@code{number-char-or-marker-p}, in @ref{Predicates on Markers}.

@defun numberp object
This predicate tests whether its argument is a number (either integer or
floating point), and returns @code{t} if so, @code{nil} otherwise.
@end defun

@defun realp object
@cindex numbers
The @code{realp} predicate tests to see whether @var{object} is a
rational or floating point number, and returns @code{t} if so,
@code{nil} otherwise.  Currently equivalent to @code{numberp}.
@end defun

@defun zerop number
This predicate tests whether its argument is zero, and returns @code{t}
if so, @code{nil} otherwise.  The argument must be a number.

These two forms are equivalent: @code{(zerop x)} @equiv{} @code{(= x 0)}.
@end defun

@defun integerp object
This predicate tests whether its argument is an integer, and returns
@code{t} if so, @code{nil} otherwise.
@end defun

@defun oddp integer
@cindex integers
The @code{oddp} predicate tests to see whether @var{integer} is odd, and
returns @code{t} if so, @code{nil} otherwise.  @var{integer} must be an
integer.
@end defun

@defun evenp integer
@cindex integers
The @code{evenp} predicate tests to see whether @var{integer} is even,
and returns @code{t} if so, @code{nil} otherwise.  @var{integer} must be
an integer.
@end defun

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

@defun fixnump object
@cindex integers
The @code{} predicate tests to see whether its argument is an integer
represented as a fixnum, and returns @code{t} if so, @code{nil}
otherwise.
@end defun

@defun bignump object
@cindex integers
The @code{bignump} predicate tests to see whether @var{object} is an
integer represented as a bignum, and returns @code{t} if so, @code{nil}
otherwise.
@end defun

@defun rationalp object
@cindex numbers
The @code{rationalp} predicate tests to see whether @var{object} is a
rational number, and returns @code{t} if so, @code{nil} otherwise.
@end defun

@defun ratiop object
@cindex ratios
The @code{ratiop} predicate tests to see whether @var{object} is a
number represented as a ratio, and returns @code{t} if so, @code{nil}
otherwise.
@end defun

@defun floatingp object
@cindex floats
The @code{floatingp} predicate tests to see whether @var{object} is a
floating point number represented as a float or a bigfloat, and returns
@code{t} if so, @code{nil} otherwise.
@end defun

@defun floatp object
@cindex floats
This predicate tests whether its argument is a floating point
number and returns @code{t} if so, @code{nil} otherwise.

@code{floatp} does not exist in Emacs versions 18 and earlier.  If the
bignum extension is present, it returns @code{nil} for a bigfloat.
@end defun

@defun bigfloatp object
@cindex floats
The @code{bigfloatp} predicate tests to see whether @var{object} is an
floating point number represented as a bigfloat, and returns @code{t} if
so, @code{nil} otherwise.
@end defun


@node Comparison of Numbers, Numeric Conversions, Predicates on Numbers, Numbers
@section Comparison of Numbers
@cindex number equality

  To test numbers for numerical equality, you should normally use
@code{=}, not @code{eq}.  There can be many distinct floating point,
bignum, and ratio number objects with the same numeric value.  If you
use @code{eq} to compare them, then you test whether two values are the
same @emph{object}.  By contrast, @code{=} 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, @code{eq} was equivalent to @code{=}
where integers are concerned.  Even with the introduction of bignums, it
is sometimes convenient to use @code{eq} for comparing an unknown value
with an integer, because @code{eq} does not report an error if the
unknown value is not a number---it accepts arguments of any type.  By
contrast, @code{=} signals an error if the arguments are not numbers or
markers.  However, it is a good idea to use @code{=} if you can, even
for comparing exact values, because two bignums or ratios with the same
value will often not be the same object.

On the other hand, some functions, such as the string- and
buffer-searching functions, will return an integer on success, but
something else (usually @code{nil}) on failure.  If it is known what the
numerical subtype (float, bigfloat, or exact) of the returned object
will be if it is a number, then the predicate @code{eql} can be used for
comparison without signaling an error on some expected return values.
Because of canonicalization, @code{eql} can be used to compare a fixnum
value to something that might be a ratio; if the potential ratio value
is representable as a fixnum, it will be canonicalized to fixnum before
comparing.  However, although floats and bigfloats are of different
types for the purpose of comparisons via @code{eql}, two bigfloats of
different @emph{precision} that are @code{=} will always be @code{eql}.

@example
(eql 2 (string-match "ere" "there"))
    @result{} t

(eql 2 (string-match "ere" "three"))
    @result{} nil

(eql 2 2.0)
    @result{} nil

(= 2 (string-match "ere" "there"))
    @result{} t

(= 2 (string-match "ere" "three"))
    @error{} Wrong type argument: number-char-or-marker-p, nil

(= 2 2.0)
    @result{} t
@end example



  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:

@example
(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)))
@end example

@cindex CL note---integers vrs @code{eq}
@quotation
@b{Common Lisp note:} Comparing numbers in Common Lisp always requires
@code{=} because Common Lisp implements multi-word integers, and two
distinct integer objects can have the same numeric value.  XEmacs Lisp
can have just one fixnum object for any given value because it has a
limited range of fixnum values.
@end quotation

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

@defun =  number &rest more-numbers
This function returns @code{t} if all of its arguments are numerically
equal, @code{nil} otherwise.

@example
(= 5)
     @result{} t
(= 5 6)
     @result{} nil
(= 5 5.0)
     @result{} t
(= 5 5 6)
     @result{} nil
@end example
@end defun

@defun /=  number &rest more-numbers
This function returns @code{t} if no two arguments are numerically
equal, @code{nil} otherwise.

@example
(/= 5 6)
     @result{} t
(/= 5 5 6)
     @result{} nil
(/= 5 6 1)
     @result{} t
@end example
@end defun

@defun <  number &rest more-numbers
This function returns @code{t} if the sequence of its arguments is
monotonically increasing, @code{nil} otherwise.

@example
(< 5 6)
     @result{} t
(< 5 6 6)
     @result{} nil
(< 5 6 7)
     @result{} t
@end example
@end defun

@defun <=  number &rest more-numbers
This function returns @code{t} if the sequence of its arguments is
monotonically nondecreasing, @code{nil} otherwise.

@example
(<= 5 6)
     @result{} t
(<= 5 6 6)
     @result{} t
(<= 5 6 5)
     @result{} nil
@end example
@end defun

@defun >  number &rest more-numbers
This function returns @code{t} if the sequence of its arguments is
monotonically decreasing, @code{nil} otherwise.
@end defun

@defun >=  number &rest more-numbers
This function returns @code{t} if the sequence of its arguments is
monotonically nonincreasing, @code{nil} otherwise.
@end defun

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

@example
(max 20)
     @result{} 20
(max 1 2.5)
     @result{} 2.5
(max 1 3 2.5)
     @result{} 3
@end example
@end defun

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

@example
(min -4 1)
     @result{} -4
@end example
@end defun

@node Numeric Conversions, Arithmetic Operations, Comparison of Numbers, Numbers
@section Numeric Conversions
@cindex rounding in conversions

To convert an integer to floating point, use the function @code{float}.

@defun float number
This returns @var{number} converted to floating point.
If @var{number} is already a floating point number, @code{float} returns
it unchanged.
@end defun

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.  They return multiple values,
@pxref{(cl.info)Multiple values}.

All these functions take optional @var{divisor} arguments, and if this
argument is specified, the @var{number} argument is divided by
@var{divisor} before the calculation is made.  An @code{arith-error}
results if @var{divisor} is 0.

@defun truncate number &optional divisor
This returns @var{number}, converted to an integer by rounding towards
zero.
@end defun

@defun floor number &optional divisor
This returns @var{number}, converted to an integer by rounding downward
(towards negative infinity).
@end defun

@defun ceiling number &optional divisor
This returns @var{number}, converted to an integer by rounding upward
(towards positive infinity).
@end defun

@defun round number &optional divisor
This returns @var{number}, converted to an integer by rounding towards the
nearest integer.

Rounding a value equidistant between two integers chooses the even
integer.  GNU Emacs and older XEmacs did not guarantee this, and the
direction of rounding depended on the underlying machine and the C
implementation.
@end defun

@node Arithmetic Operations, Rounding Operations, Numeric Conversions, Numbers
@section 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 @code{%} 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 @code{(1+ 134217727)} may evaluate to
@minus{}134217728, depending on your hardware and whether your XEmacs
supports bignums.

@defun 1+ number
This function returns @var{number} plus one.  @var{number} may be a
number, character or marker.  Markers and characters are converted to
integers.

For example,

@example
(setq foo 4)
     @result{} 4
(1+ foo)
     @result{} 5
@end example

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

@example
foo
     @result{} 4
@end example

If you want to increment the variable, you must use @code{setq},
like this:

@example
(setq foo (1+ foo))
     @result{} 5
@end example

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

@defun 1- number
This function returns @var{number} minus one.  @var{number} may be a
number, character or marker.  Markers and characters are converted to
integers.
@end defun

@defun abs number
This returns the absolute value of @var{number}.
@end defun

@defun + &rest numbers
This function adds its arguments together.  When given no arguments,
@code{+} returns 0.

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

@example
(+)
     @result{} 0
(+ 1)
     @result{} 1
(+ 1 2 3 4)
     @result{} 10
@end example
@end defun

@defun - &optional number &rest other-numbers
The @code{-} function serves two purposes: negation and subtraction.
When @code{-} has a single argument, the value is the negative of the
argument.  When there are multiple arguments, @code{-} subtracts each of
the @var{other-numbers} from @var{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.

@example
(- 10 1 2 3 4)
     @result{} 0
(- 10)
     @result{} -10
(-)
     @result{} 0
@end example
@end defun

@defun * &rest numbers
This function multiplies its arguments together, and returns the
product.  When given no arguments, @code{*} returns 1.

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

@example
(*)
     @result{} 1
(* 1)
     @result{} 1
(* 1 2 3 4)
     @result{} 24
@end example
@end defun

@defun / dividend &rest divisors
The @code{/} function serves two purposes: inversion and division.  When
@code{/} has a single argument, the value is the inverse of the
argument.  When there are multiple arguments, @code{/} divides
@var{dividend} by each of the @var{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
@code{/} 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.

@cindex @code{arith-error} in division
If you divide by 0, an @code{arith-error} error is signaled.
(@xref{Errors}.)

@example
@group
(/ 6 2)
     @result{} 3
@end group
(/ 5 2)
     @result{} 2
(/ 25 3 2)
     @result{} 4
(/ 3.0)
     @result{} 0.3333333333333333
(/ -17 6)
     @result{} -2
@end example

The result of @code{(/ -17 6)} could in principle be -3 on some
machines.
@end defun

@defun % dividend divisor
@cindex remainder
This function returns the integer remainder after division of @var{dividend}
by @var{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 @code{arith-error} results if @var{divisor} is 0.

@example
(% 9 4)
     @result{} 1
(% -9 4)
     @result{} -1
(% 9 -4)
     @result{} 1
(% -9 -4)
     @result{} -1
@end example

For any two integers @var{dividend} and @var{divisor},

@example
@group
(+ (% @var{dividend} @var{divisor})
   (* (/ @var{dividend} @var{divisor}) @var{divisor}))
@end group
@end example

@noindent
always equals @var{dividend}.
@end defun

@defun mod dividend divisor
@cindex modulus
This function returns the value of @var{dividend} modulo @var{divisor};
in other words, the remainder after division of @var{dividend}
by @var{divisor}, but with the same sign as @var{divisor}.
The arguments must be numbers or markers.

Unlike @code{%}, @code{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 @code{arith-error} results if @var{divisor} is 0.

@example
@group
(mod 9 4)
     @result{} 1
@end group
@group
(mod -9 4)
     @result{} 3
@end group
@group
(mod 9 -4)
     @result{} -3
@end group
@group
(mod -9 -4)
     @result{} -1
@end group
@group
(mod 5.5 2.5)
     @result{} .5
@end group
@end example

For any two numbers @var{dividend} and @var{divisor},

@example
@group
(+ (mod @var{dividend} @var{divisor})
   (* (floor @var{dividend} @var{divisor}) @var{divisor}))
@end group
@end example

@noindent
always equals @var{dividend}, subject to rounding error if either
argument is floating point.  For @code{floor}, see @ref{Numeric
Conversions}.
@end defun

@node Rounding Operations, Bitwise Operations, Arithmetic Operations, Numbers
@section Rounding Operations
@cindex rounding without conversion

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

All these functions take optional @var{divisor} arguments, and if this
argument is specified, the @var{number} argument is divided by
@var{divisor} before the calculation is made.  An @code{arith-error}
results if @var{divisor} is 0.  Also, they return multiple values,
@pxref{(cl.info)Multiple values}; the second value is the remainder.

@defun ffloor number &optional divisor
This function rounds @var{number} to the next lower integral value, and
returns that value as a floating point number.
@end defun

@defun fceiling number &optional divisor
This function rounds @var{number} to the next higher integral value, and
returns that value as a floating point number.
@end defun

@defun ftruncate number &optional divisor
This function rounds @var{number} towards zero to an integral value, and
returns that value as a floating point number.
@end defun

@defun fround number &optional divisor
This function rounds @var{number} to the nearest integral value,
and returns that value as a floating point number.

Rounding a value equidistant between two integral values chooses the
even value.  While this is specified by Common Lisp, GNU Emacs and older
XEmacs did not make this guarantee, and the direction of rounding
depended on the underlying machine and the C implementation.
@end defun

@node Bitwise Operations, Math Functions, Rounding Operations, Numbers
@section Bitwise Operations on Integers

  In a computer, an integer is represented as a binary number, a
sequence of @dfn{bits} (digits which are either zero or one).  A bitwise
operation acts on the individual bits of such a sequence.  For example,
@dfn{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.

@defun lsh integer1 count
@cindex logical shift
@code{lsh}, which is an abbreviation for @dfn{logical shift}, shifts the
bits in @var{integer1} to the left @var{count} places, or to the right
if @var{count} is negative, bringing zeros into the vacated bits.  If
@var{count} is negative, @code{lsh} shifts zeros into the leftmost
(most-significant) bit, producing a positive result even if
@var{integer1} is negative.  Contrast this with @code{ash}, below.

Here are two examples of @code{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.

@example
@group
(lsh 5 1)
     @result{} 10
;; @r{Decimal 5 becomes decimal 10.}
00000101 @result{} 00001010

(lsh 7 1)
     @result{} 14
;; @r{Decimal 7 becomes decimal 14.}
00000111 @result{} 00001110
@end group
@end example

@noindent
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):

@example
@group
(lsh 3 2)
     @result{} 12
;; @r{Decimal 3 becomes decimal 12.}
00000011 @result{} 00001100
@end group
@end example

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

@example
@group
(lsh 6 -1)
     @result{} 3
;; @r{Decimal 6 becomes decimal 3.}
00000110 @result{} 00000011
@end group

@group
(lsh 5 -1)
     @result{} 2
;; @r{Decimal 5 becomes decimal 2.}
00000101 @result{} 00000010
@end group
@end example

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

The function @code{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 @minus{}2 on a 28-bit machine:

@example
(lsh 134217727 1)          ; @r{left shift}
     @result{} -2
@end example

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

@example
@group
;; @r{Decimal 134,217,727}
0111  1111 1111  1111 1111  1111 1111
@end group
@end example

@noindent
which becomes the following when left shifted:

@example
@group
;; @r{Decimal @minus{}2}
1111  1111 1111  1111 1111  1111 1110
@end group
@end example
@end defun

@defun ash integer1 count
@cindex arithmetic shift
@code{ash} (@dfn{arithmetic shift}) shifts the bits in @var{integer1}
to the left @var{count} places, or to the right if @var{count}
is negative.

@code{ash} gives the same results as @code{lsh} except when
@var{integer1} and @var{count} are both negative.  In that case,
@code{ash} puts ones in the empty bit positions on the left, while
@code{lsh} puts zeros in those bit positions.

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

@example
@group
(ash -6 -1) @result{} -3
;; @r{Decimal @minus{}6 becomes decimal @minus{}3.}
1111  1111 1111  1111 1111  1111 1010
     @result{}
1111  1111 1111  1111 1111  1111 1101
@end group
@end example

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

@example
@group
(lsh -6 -1) @result{} 134217725
;; @r{Decimal @minus{}6 becomes decimal 134,217,725.}
1111  1111 1111  1111 1111  1111 1010
     @result{}
0111  1111 1111  1111 1111  1111 1101
@end group
@end example

Here are other examples:

@c !!! Check if lined up in smallbook format!  XDVI shows problem
@c     with smallbook but not with regular book! --rjc 16mar92
@smallexample
@group
                   ;  @r{             28-bit binary values}

(lsh 5 2)          ;   5  =  @r{0000  0000 0000  0000 0000  0000 0101}
     @result{} 20         ;      =  @r{0000  0000 0000  0000 0000  0001 0100}
@end group
@group
(ash 5 2)
     @result{} 20
(lsh -5 2)         ;  -5  =  @r{1111  1111 1111  1111 1111  1111 1011}
     @result{} -20        ;      =  @r{1111  1111 1111  1111 1111  1110 1100}
(ash -5 2)
     @result{} -20
@end group
@group
(lsh 5 -2)         ;   5  =  @r{0000  0000 0000  0000 0000  0000 0101}
     @result{} 1          ;      =  @r{0000  0000 0000  0000 0000  0000 0001}
@end group
@group
(ash 5 -2)
     @result{} 1
@end group
@group
(lsh -5 -2)        ;  -5  =  @r{1111  1111 1111  1111 1111  1111 1011}
     @result{} 4194302    ;      =  @r{0011  1111 1111  1111 1111  1111 1110}
@end group
@group
(ash -5 -2)        ;  -5  =  @r{1111  1111 1111  1111 1111  1111 1011}
     @result{} -2         ;      =  @r{1111  1111 1111  1111 1111  1111 1110}
@end group
@end smallexample
@end defun

@defun logand &rest ints-or-markers
@cindex logical and
@cindex bitwise and
This function returns the ``logical and'' of the arguments: the
@var{n}th bit is set in the result if, and only if, the @var{n}th 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.

@noindent
Therefore,

@example
@group
(logand 13 12)
     @result{} 12
@end group
@end example

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

@smallexample
@group
                   ; @r{               28-bit binary values}

(logand 14 13)     ; 14  =  @r{0000  0000 0000  0000 0000  0000 1110}
                   ; 13  =  @r{0000  0000 0000  0000 0000  0000 1101}
     @result{} 12         ; 12  =  @r{0000  0000 0000  0000 0000  0000 1100}
@end group

@group
(logand 14 13 4)   ; 14  =  @r{0000  0000 0000  0000 0000  0000 1110}
                   ; 13  =  @r{0000  0000 0000  0000 0000  0000 1101}
                   ;  4  =  @r{0000  0000 0000  0000 0000  0000 0100}
     @result{} 4          ;  4  =  @r{0000  0000 0000  0000 0000  0000 0100}
@end group

@group
(logand)
     @result{} -1         ; -1  =  @r{1111  1111 1111  1111 1111  1111 1111}
@end group
@end smallexample
@end defun

@defun logior &rest ints-or-markers
@cindex logical inclusive or
@cindex bitwise or
This function returns the ``inclusive or'' of its arguments: the @var{n}th bit
is set in the result if, and only if, the @var{n}th 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 @code{logior} is
passed just one argument, it returns that argument.

@smallexample
@group
                   ; @r{              28-bit binary values}

(logior 12 5)      ; 12  =  @r{0000  0000 0000  0000 0000  0000 1100}
                   ;  5  =  @r{0000  0000 0000  0000 0000  0000 0101}
     @result{} 13         ; 13  =  @r{0000  0000 0000  0000 0000  0000 1101}
@end group

@group
(logior 12 5 7)    ; 12  =  @r{0000  0000 0000  0000 0000  0000 1100}
                   ;  5  =  @r{0000  0000 0000  0000 0000  0000 0101}
                   ;  7  =  @r{0000  0000 0000  0000 0000  0000 0111}
     @result{} 15         ; 15  =  @r{0000  0000 0000  0000 0000  0000 1111}
@end group
@end smallexample
@end defun

@defun logxor &rest ints-or-markers
@cindex bitwise exclusive or
@cindex logical exclusive or
This function returns the ``exclusive or'' of its arguments: the
@var{n}th bit is set in the result if, and only if, the @var{n}th 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
@code{logxor} is passed just one argument, it returns that argument.

@smallexample
@group
                   ; @r{              28-bit binary values}

(logxor 12 5)      ; 12  =  @r{0000  0000 0000  0000 0000  0000 1100}
                   ;  5  =  @r{0000  0000 0000  0000 0000  0000 0101}
     @result{} 9          ;  9  =  @r{0000  0000 0000  0000 0000  0000 1001}
@end group

@group
(logxor 12 5 7)    ; 12  =  @r{0000  0000 0000  0000 0000  0000 1100}
                   ;  5  =  @r{0000  0000 0000  0000 0000  0000 0101}
                   ;  7  =  @r{0000  0000 0000  0000 0000  0000 0111}
     @result{} 14         ; 14  =  @r{0000  0000 0000  0000 0000  0000 1110}
@end group
@end smallexample
@end defun

@defun lognot integer
@cindex logical not
@cindex bitwise not
This function returns the logical complement of its argument: the @var{n}th
bit is one in the result if, and only if, the @var{n}th bit is zero in
@var{integer}, and vice-versa.

@example
(lognot 5)
     @result{} -6
;;  5  =  @r{0000  0000 0000  0000 0000  0000 0101}
;; @r{becomes}
;; -6  =  @r{1111  1111 1111  1111 1111  1111 1010}
@end example
@end defun

@node Math Functions, Random Numbers, Bitwise Operations, Numbers
@section Standard Mathematical Functions
@cindex transcendental functions
@cindex 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.

@defun sin number
@defunx cos number
@defunx tan number
These are the ordinary trigonometric functions, with argument measured
in radians.
@end defun

@defun asin number
The value of @code{(asin @var{number})} is a number between @minus{}pi/2
and pi/2 (inclusive) whose sine is @var{number}; if, however, @var{number}
is out of range (outside [-1, 1]), then the result is a NaN.
@end defun

@defun acos number
The value of @code{(acos @var{number})} is a number between 0 and pi
(inclusive) whose cosine is @var{number}; if, however, @var{number}
is out of range (outside [-1, 1]), then the result is a NaN.
@end defun

@defun atan number &optional number2
The value of @code{(atan @var{number})} is a number between @minus{}pi/2
and pi/2 (exclusive) whose tangent is @var{number}.

If optional argument @var{number2} is supplied, the function returns
@code{atan2(@var{number},@var{number2})}.
@end defun

@defun sinh number
@defunx cosh number
@defunx tanh number
These are the ordinary hyperbolic trigonometric functions.
@end defun

@defun asinh number
@defunx acosh number
@defunx atanh number
These are the inverse hyperbolic trigonometric functions.
@end defun

@defun exp number
This is the exponential function; it returns @i{e} to the power
@var{number}.  @i{e} is a fundamental mathematical constant also called the
base of natural logarithms.
@end defun

@defun log number &optional base
This function returns the logarithm of @var{number}, with base @var{base}.
If you don't specify @var{base}, the base @code{e} is used.  If @var{number}
is negative, the result is a NaN.
@end defun

@defun log10 number
This function returns the logarithm of @var{number}, with base 10.  If
@var{number} is negative, the result is a NaN.  @code{(log10 @var{x})}
@equiv{} @code{(log @var{x} 10)}, at least approximately.
@end defun

@defun expt x y
This function returns @var{x} raised to power @var{y}.  If both
arguments are integers and @var{y} is positive, the result is an
integer; in this case, it is truncated to fit the range of possible
integer values.
@end defun

@defun sqrt number
This returns the square root of @var{number}.  If @var{number} is negative,
the value is a NaN.
@end defun

@defun cube-root number
This returns the cube root of @var{number}.
@end defun

@node Random Numbers,  , Math Functions, Numbers
@section Random Numbers
@cindex random numbers

A deterministic computer program cannot generate true random numbers.
For most purposes, @dfn{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 @code{random} function always
generates the same sequence of numbers.  XEmacs always starts with the
same seed value, so the sequence of values of @code{random} is actually
the same in each XEmacs run!  For example, in one operating system, the
first call to @code{(random)} after you start XEmacs always returns
-1457731, and the second one always returns -7692030.  This
repeatability is helpful for debugging.

If you want reasonably unpredictable random numbers, execute
@code{(random t)}.  This chooses a new seed based on the current time of
day and on XEmacs's process @sc{id} number.  (This is not
cryptographically strong, it's just hard for a @emph{human} to
anticipate.)

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

If @var{limit} is a positive integer, the value is chosen to be
nonnegative and less than @var{limit}.

If @var{limit} is @code{t}, it means to choose a new seed based on the
current time of day and on XEmacs's process @sc{id} number.
@c "XEmacs'" is incorrect usage!
@end defun

The range of random is implementation-dependent.  On any machine, the
result of @code{(random)} is an arbitrary fixnum, so on 32-bit
architectures it is normally in the range -2^30 (inclusive) to +2^30
(exclusive).  With the optional integer argument @var{limit}, the result
is in the range 0 (inclusive) to @var{limit} (exclusive).  Note this is
regardless of the presence of the bignum extension.

