view man/lispref/numbers.texi @ 5353:38e24b8be4ea

Improve the lexical scoping in #'block, #'return-from. lisp/ChangeLog addition: 2011-02-07 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el: * bytecomp.el (byte-compile-initial-macro-environment): Shadow `block', `return-from' here, we implement them differently when byte-compiling. * bytecomp.el (byte-compile-active-blocks): New. * bytecomp.el (byte-compile-block-1): New. * bytecomp.el (byte-compile-return-from-1): New. * bytecomp.el (return-from-1): New. * bytecomp.el (block-1): New. These are two aliases that exist to have their own associated byte-compile functions, which functions implement `block' and `return-from'. * cl-extra.el (cl-macroexpand-all): Fix a bug here when macros in the environment have been compiled. * cl-macs.el (block): * cl-macs.el (return): * cl-macs.el (return-from): Be more careful about lexical scope in these macros. * cl.el: * cl.el ('cl-block-wrapper): Removed. * cl.el ('cl-block-throw): Removed. These aren't needed in code generated by this XEmacs. They shouldn't be needed in code generated by XEmacs 21.4, but if it turns out the packages do need them, we can put them back. 2011-01-30 Mike Sperber <mike@xemacs.org> * font-lock.el (font-lock-fontify-pending-extents): Don't fail if `font-lock-mode' is unset, which can happen in the middle of `revert-buffer'. 2011-01-23 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (delete): * cl-macs.el (delq): * cl-macs.el (remove): * cl-macs.el (remq): Don't use the compiler macro if these functions were given the wrong number of arguments, as happens in lisp-tests.el. * cl-seq.el (remove, remq): Removed. I added these to subr.el, and forgot to remove them from here. 2011-01-22 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-setq, byte-compile-set): Remove kludge allowing keywords' values to be set, all the code that does that is gone. * cl-compat.el (elt-satisfies-test-p): * faces.el (set-face-parent): * faces.el (face-doc-string): * gtk-font-menu.el: * gtk-font-menu.el (gtk-reset-device-font-menus): * msw-font-menu.el: * msw-font-menu.el (mswindows-reset-device-font-menus): * package-get.el (package-get-installedp): * select.el (select-convert-from-image-data): * sound.el: * sound.el (load-sound-file): * x-font-menu.el (x-reset-device-font-menus-core): Don't quote keywords, they're self-quoting, and the win from backward-compatibility is sufficiently small now that the style problem overrides it. 2011-01-22 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (block, return-from): Require that NAME be a symbol in these macros, as always documented in the #'block docstring and as required by Common Lisp. * descr-text.el (unidata-initialize-unihan-database): Correct the use of non-symbols in #'block and #'return-from in this function. 2011-01-15 Aidan Kehoe <kehoea@parhasard.net> * cl-extra.el (concatenate): Accept more complicated TYPEs in this function, handing the sequences over to #'coerce if we don't understand them here. * cl-macs.el (inline): Don't proclaim #'concatenate as inline, its compiler macro is more useful than doing that. 2011-01-11 Aidan Kehoe <kehoea@parhasard.net> * subr.el (delete, delq, remove, remq): Move #'remove, #'remq here, they don't belong in cl-seq.el; move #'delete, #'delq here from fns.c, implement them in terms of #'delete*, allowing support for sequences generally. * update-elc.el (do-autoload-commands): Use #'delete*, not #'delq here, now the latter's no longer dumped. * cl-macs.el (delete, delq): Add compiler macros transforming #'delete and #'delq to #'delete* calls. 2011-01-10 Aidan Kehoe <kehoea@parhasard.net> * dialog.el (make-dialog-box): Correct a misplaced parenthesis here, thank you Mats Lidell in 87zkr9gqrh.fsf@mail.contactor.se ! 2011-01-02 Aidan Kehoe <kehoea@parhasard.net> * dialog.el (make-dialog-box): * list-mode.el (display-completion-list): These functions used to use cl-parsing-keywords; change them to use defun* instead, fixing the build. (Not sure what led to me not including this change in d1b17a33450b!) 2011-01-02 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (define-star-compiler-macros): Make sure the form has ITEM and LIST specified before attempting to change to calls with explicit tests; necessary for some tests in lisp-tests.el to compile correctly. (stable-union, stable-intersection): Add compiler macros for these functions, in the same way we do for most of the other functions in cl-seq.el. 2011-01-01 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (dolist, dotimes, do-symbols, macrolet) (symbol-macrolet): Define these macros with defmacro* instead of parsing the argument list by hand, for the sake of style and readability; use backquote where appropriate, instead of calling #'list and and friends, for the same reason. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * x-misc.el (device-x-display): Provide this function, documented in the Lispref for years, but not existing previously. Thank you Julian Bradfield, thank you Jeff Mincy. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * cl-seq.el: Move the heavy lifting from this file to C. Dump the cl-parsing-keywords macro, but don't use defun* for the functions we define that do take keywords, dynamic scope lossage makes that not practical. * subr.el (sort, fillarray): Move these aliases here. (map-plist): #'nsublis is now built-in, but at this point #'eql isn't necessarily available as a test; use #'eq. * obsolete.el (cl-delete-duplicates): Make this available for old compiler macros and old code. (memql): Document that this is equivalent to #'member*, and worse. * cl.el (adjoin, subst): Removed. These are in C. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * simple.el (assoc-ignore-case): Remove a duplicate definition of this function (it's already in subr.el). * iso8859-1.el (char-width): On non-Mule, make this function equivalent to that produced by (constantly 1), but preserve its docstring. * subr.el (subst-char-in-string): Define this in terms of #'substitute, #'nsubstitute. (string-width): Define this using #'reduce and #'char-width. (char-width): Give this a simpler definition, it makes far more sense to check for mule at load time and redefine, as we do in iso8859-1.el. (store-substring): Implement this in terms of #'replace, now #'replace is cheap. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * update-elc.el (lisp-files-needed-for-byte-compilation) (lisp-files-needing-early-byte-compilation): cl-macs belongs in the former, not the latter, it is as fundamental as bytecomp.el. 2010-12-30 Aidan Kehoe <kehoea@parhasard.net> * cl.el: Provde the Common Lisp program-error, type-error as error symbols. This doesn't nearly go far enough for anyone using the Common Lisp errors. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (delete-duplicates): If the form has an incorrect number of arguments, don't attempt a compiler macroexpansion. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (cl-safe-expr-p): Forms that start with the symbol lambda are also safe. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (= < > <= >=): For these functions' compiler macros, the optimisation is safe even if the first and the last arguments have side effects, since they're only used the once. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (inline-side-effect-free-compiler-macros): Unroll a loop here at macro-expansion time, so these compiler macros are compiled. Use #'eql instead of #'eq in a couple of places for better style. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * cl-extra.el (notany, notevery): Avoid some dynamic scope stupidity with local variable names in these functions, when they weren't prefixed with cl-; go into some more detail in the doc strings. 2010-12-29 Aidan Kehoe <kehoea@parhasard.net> * byte-optimize.el (side-effect-free-fns): #'remove, #'remq are free of side-effects. (side-effect-and-error-free-fns): Drop dot, dot-marker from the list. 2010-11-17 Aidan Kehoe <kehoea@parhasard.net> * cl-extra.el (coerce): In the argument list, name the first argument OBJECT, not X; the former name was always used in the doc string and is clearer. Handle vector type specifications which include the length of the target sequence, error if there's a mismatch. * cl-macs.el (cl-make-type-test): Handle type specifications starting with the symbol 'eql. 2010-11-14 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (eql): Don't remove the byte-compile property of this symbol. That was necessary to override a bug in bytecomp.el where #'eql was confused with #'eq, which bug we no longer have. If neither expression is constant, don't attempt to handle the expression in this compiler macro, leave it to byte-compile-eql, which produces better code anyway. * bytecomp.el (eq): #'eql is not the function associated with the byte-eq byte code. (byte-compile-eql): Add an explicit compile method for this function, for cases where the cl-macs compiler macro hasn't reduced it to #'eq or #'equal. 2010-10-25 Aidan Kehoe <kehoea@parhasard.net> Add compiler macros and compilation sanity-checking for various functions that take keywords. * byte-optimize.el (side-effect-free-fns): #'symbol-value is side-effect free and not error free. * bytecomp.el (byte-compile-normal-call): Check keyword argument lists for sanity; store information about the positions where keyword arguments start using the new byte-compile-keyword-start property. * cl-macs.el (cl-const-expr-val): Take a new optional argument, cl-not-constant, defaulting to nil, in this function; return it if the expression is not constant. (cl-non-fixnum-number-p): Make this into a separate function, we want to pass it to #'every. (eql): Use it. (define-star-compiler-macros): Use the same code to generate the member*, assoc* and rassoc* compiler macros; special-case some code in #'add-to-list in subr.el. (remove, remq): Add compiler macros for these two functions, in preparation for #'remove being in C. (define-foo-if-compiler-macros): Transform (remove-if-not ...) calls to (remove ... :if-not) at compile time, which will be a real win once the latter is in C. (define-substitute-if-compiler-macros) (define-subst-if-compiler-macros): Similarly for these functions. (delete-duplicates): Change this compiler macro to use #'plists-equal; if we don't have information about the type of SEQUENCE at compile time, don't bother attempting to inline the call, the function will be in C soon enough. (equalp): Remove an old commented-out compiler macro for this, if we want to see it it's in version control. (subst-char-in-string): Transform this to a call to nsubstitute or nsubstitute, if that is appropriate. * cl.el (ldiff): Don't call setf here, this makes for a load-time dependency problem in cl-macs.el 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * term/vt100.el: Refer to XEmacs, not GNU Emacs, in permissions. * term/bg-mouse.el: * term/sup-mouse.el: Put copyright notice in canonical "Copyright DATE AUTHOR" form. Refer to XEmacs, not GNU Emacs, in permissions. * site-load.el: Add permission boilerplate. * mule/canna-leim.el: * alist.el: Refer to XEmacs, not APEL/this program, in permissions. * mule/canna-leim.el: Remove my copyright, I've assigned it to the FSF. 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * gtk.el: * gtk-widget-accessors.el: * gtk-package.el: * gtk-marshal.el: * gtk-compose.el: * gnome.el: Add copyright notice based on internal evidence. 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * easymenu.el: Add reference to COPYING to permission notice. * gutter.el: * gutter-items.el: * menubar-items.el: Fix typo "Xmacs" in permissions notice. 2010-06-14 Stephen J. Turnbull <stephen@xemacs.org> * auto-save.el: * font.el: * fontconfig.el: * mule/kinsoku.el: Add "part of XEmacs" text to permission notice. 2010-10-14 Aidan Kehoe <kehoea@parhasard.net> * byte-optimize.el (side-effect-free-fns): * cl-macs.el (remf, getf): * cl-extra.el (tailp, cl-set-getf, cl-do-remf): * cl.el (ldiff, endp): Tighten up Common Lisp compatibility for #'ldiff, #'endp, #'tailp; add circularity checking for the first two. #'cl-set-getf and #'cl-do-remf were Lisp implementations of #'plist-put and #'plist-remprop; change the names to aliases, changes the macros that use them to using #'plist-put and #'plist-remprop directly. 2010-10-12 Aidan Kehoe <kehoea@parhasard.net> * abbrev.el (fundamental-mode-abbrev-table, global-abbrev-table): Create both these abbrev tables using the usual #'define-abbrev-table calls, rather than attempting to special-case them. * cl-extra.el: Force cl-macs to be loaded here, if cl-extra.el is being loaded interpreted. Previously other, later files would redundantly call (load "cl-macs") when interpreted, it's more reasonable to do it here, once. * cmdloop.el (read-quoted-char-radix): Use defcustom here, we don't have any dump-order dependencies that would prevent that. * custom.el (eval-when-compile): Don't load cl-macs when interpreted or when byte-compiling, rely on cl-extra.el in the former case and the appropriate entry in bytecomp-load-hook in the latter. Get rid of custom-declare-variable-list, we have no dump-time dependencies that would require it. * faces.el (eval-when-compile): Don't load cl-macs when interpreted or when byte-compiling. * packages.el: Remove some inaccurate comments. * post-gc.el (cleanup-simple-finalizers): Use #'delete-if-not here, now the order of preloaded-file-list has been changed to make it available. * subr.el (custom-declare-variable-list): Remove. No need for it. Also remove a stub define-abbrev-table from this file, given the current order of preloaded-file-list there's no need for it. 2010-10-10 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-constp) Forms quoted with FUNCTION are also constant. (byte-compile-initial-macro-environment): In #'the, if FORM is constant and does not match TYPE, warn at byte-compile time. 2010-10-10 Aidan Kehoe <kehoea@parhasard.net> * backquote.el (bq-vector-contents, bq-list*): Remove; the former is equivalent to (append VECTOR nil), the latter to (list* ...). (bq-process-2): Use (append VECTOR nil) instead of using #'bq-vector-contents to convert to a list. (bq-process-1): Now we use list* instead of bq-list * subr.el (list*): Moved from cl.el, since it is now required to be available the first time a backquoted form is encountered. * cl.el (list*): Move to subr.el. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * test-harness.el (Check-Message): Add an omitted comma here, thank you the buildbot. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * hash-table.el (hash-table-key-list, hash-table-value-list) (hash-table-key-value-alist, hash-table-key-value-plist): Remove some useless #'nreverse calls in these files; our hash tables have no order, it's not helpful to pretend they do. * behavior.el (read-behavior): Do the same in this file, in some code evidently copied from hash-table.el. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * info.el (Info-insert-dir): * format.el (format-deannotate-region): * files.el (cd, save-buffers-kill-emacs): Use #'some, #'every and related functions for applying boolean operations to lists, instead of rolling our own ones that cons and don't short-circuit. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-initial-macro-environment): * cl-macs.el (the): Rephrase the docstring, make its implementation when compiling files a little nicer. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * descr-text.el (unidata-initialize-unicodedata-database) (unidata-initialize-unihan-database, describe-char-unicode-data) (describe-char-unicode-data): Wrap calls to the database functions with (with-fboundp ...), avoiding byte compile warnings on builds without support for the database functions. (describe-char): (reduce #'max ...), not (apply #'max ...), no need to cons needlessly. (describe-char): Remove a redundant lambda wrapping #'extent-properties. (describe-char-unicode-data): Call #'nsubst when replacing "" with nil in the result of #'split-string, instead of consing inside mapcar. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * x-faces.el (x-available-font-sizes): * specifier.el (let-specifier): * package-ui.el (pui-add-required-packages): * msw-faces.el (mswindows-available-font-sizes): * modeline.el (modeline-minor-mode-menu): * minibuf.el (minibuf-directory-files): Replace the O2N (delq nil (mapcar (lambda (W) (and X Y)) Z)) with the ON (mapcan (lambda (W) (and X (list Y))) Z) in these files. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * cl-macs.el (= < > <= >=): When these functions are handed more than two arguments, and those arguments have no side effects, transform to a series of two argument calls, avoiding funcall in the byte-compiled code. * mule/mule-cmds.el (finish-set-language-environment): Take advantage of this change in a function called 256 times at startup. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * bytecomp.el (byte-compile-function-form, byte-compile-quote) (byte-compile-quote-form): Warn at compile time, and error at runtime, if a (quote ...) or a (function ...) form attempts to quote more than one object. 2010-09-16 Aidan Kehoe <kehoea@parhasard.net> * byte-optimize.el (byte-optimize-apply): Transform (apply 'nconc (mapcar ...)) to (mapcan ...); warn about use of the first idiom. * update-elc.el (do-autoload-commands): * packages.el (packages-find-package-library-path): * frame.el (frame-list): * extents.el (extent-descendants): * etags.el (buffer-tag-table-files): * dumped-lisp.el (preloaded-file-list): * device.el (device-list): * bytecomp-runtime.el (proclaim-inline, proclaim-notinline) Use #'mapcan, not (apply #'nconc (mapcar ...) in all these files. * bytecomp-runtime.el (eval-when-compile, eval-and-compile): In passing, mention that these macros also evaluate the body when interpreted. tests/ChangeLog addition: 2011-02-07 Aidan Kehoe <kehoea@parhasard.net> * automated/lisp-tests.el: Test lexical scope for `block', `return-from'; add a Known-Bug-Expect-Failure for a contorted example that fails when byte-compiled.
author Aidan Kehoe <kehoea@parhasard.net>
date Mon, 07 Feb 2011 12:01:24 +0000
parents 378a34562cbe
children a2912073be85
line wrap: on
line source

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

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

  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 @samp{--use-number-lib=gmp} (respectively
@samp{--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 @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, 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://www.swox.com/gmp/gmp-speed.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}.

  Bignum support is incomplete.  If you would like to help with bignum
support, especially on BSD MP, please subscribe to the
@uref{http://www.xemacs.org/Lists/#xemacs-beta, XEmacs Beta mailing
list}, and book up on @file{number-gmp.h} and @file{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!

@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
@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 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 @samp{%d}, @samp{%o},
@samp{%x}, and @samp{%u} format conversions.


@node Ratio Basics
@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
@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}.
@c #### is this true?
Bigfloats are created automatically when a number with yes



@node Canonicalization and Contagion
@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
@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
@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
@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
@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
@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
@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
@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
@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
@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.