Merge branch 'master' of git.sv.gnu.org:/srv/git/emacs
[emacs.git] / doc / lispref / numbers.texi
blobc2cb6651d4715f4c625be6d57e340defcec85bc7
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998-1999, 2001-2018 Free Software
4 @c Foundation, Inc.
5 @c See the file elisp.texi for copying conditions.
6 @node Numbers
7 @chapter Numbers
8 @cindex integers
9 @cindex numbers
11   GNU Emacs supports two numeric data types: @dfn{integers} and
12 @dfn{floating-point numbers}.  Integers are whole numbers such as
13 @minus{}3, 0, 7, 13, and 511.  Floating-point numbers are numbers with
14 fractional parts, such as @minus{}4.5, 0.0, and 2.71828.  They can
15 also be expressed in exponential notation: @samp{1.5e2} is the same as
16 @samp{150.0}; here, @samp{e2} stands for ten to the second power, and
17 that is multiplied by 1.5.  Integer computations are exact, though
18 they may overflow.  Floating-point computations often involve rounding
19 errors, as the numbers have a fixed amount of precision.
21 @menu
22 * Integer Basics::            Representation and range of integers.
23 * Float Basics::              Representation and range of floating point.
24 * Predicates on Numbers::     Testing for numbers.
25 * Comparison of Numbers::     Equality and inequality predicates.
26 * Numeric Conversions::       Converting float to integer and vice versa.
27 * Arithmetic Operations::     How to add, subtract, multiply and divide.
28 * Rounding Operations::       Explicitly rounding floating-point numbers.
29 * Bitwise Operations::        Logical and, or, not, shifting.
30 * Math Functions::            Trig, exponential and logarithmic functions.
31 * Random Numbers::            Obtaining random integers, predictable or not.
32 @end menu
34 @node Integer Basics
35 @section Integer Basics
37   The range of values for an integer depends on the machine.  The
38 minimum range is @minus{}536,870,912 to 536,870,911 (30 bits; i.e.,
39 @ifnottex
40 @minus{}2**29
41 @end ifnottex
42 @tex
43 @math{-2^{29}}
44 @end tex
46 @ifnottex
47 2**29 @minus{} 1),
48 @end ifnottex
49 @tex
50 @math{2^{29}-1}),
51 @end tex
52 but many machines provide a wider range.  Many examples in this
53 chapter assume the minimum integer width of 30 bits.
54 @cindex overflow
56   The Lisp reader reads an integer as a nonempty sequence
57 of decimal digits with optional initial sign and optional
58 final period.  A decimal integer that is out of the
59 Emacs range is treated as a floating-point number.
61 @example
62  1               ; @r{The integer 1.}
63  1.              ; @r{The integer 1.}
64 +1               ; @r{Also the integer 1.}
65 -1               ; @r{The integer @minus{}1.}
66  9000000000000000000
67                  ; @r{The floating-point number 9e18.}
68  0               ; @r{The integer 0.}
69 -0               ; @r{The integer 0.}
70 @end example
72 @cindex integers in specific radix
73 @cindex radix for reading an integer
74 @cindex base for reading an integer
75 @cindex hex numbers
76 @cindex octal numbers
77 @cindex reading numbers in hex, octal, and binary
78   The syntax for integers in bases other than 10 consists of @samp{#}
79 followed by a radix indication followed by one or more digits.  The
80 radix indications are @samp{b} for binary, @samp{o} for octal,
81 @samp{x} for hex, and @samp{@var{radix}r} for radix @var{radix}.
82 Thus, @samp{#b@var{integer}} reads
83 @var{integer} in binary, and @samp{#@var{radix}r@var{integer}} reads
84 @var{integer} in radix @var{radix}.  Allowed values of @var{radix} run
85 from 2 to 36, and allowed digits are the first @var{radix} characters
86 taken from @samp{0}--@samp{9}, @samp{A}--@samp{Z}.
87 Letter case is ignored and there is no initial sign or final period.
88 For example:
90 @example
91 #b101100 @result{} 44
92 #o54 @result{} 44
93 #x2c @result{} 44
94 #24r1k @result{} 44
95 @end example
97   To understand how various functions work on integers, especially the
98 bitwise operators (@pxref{Bitwise Operations}), it is often helpful to
99 view the numbers in their binary form.
101   In 30-bit binary, the decimal integer 5 looks like this:
103 @example
104 0000...000101 (30 bits total)
105 @end example
107 @noindent
108 (The @samp{...} stands for enough bits to fill out a 30-bit word; in
109 this case, @samp{...} stands for twenty 0 bits.  Later examples also
110 use the @samp{...} notation to make binary integers easier to read.)
112   The integer @minus{}1 looks like this:
114 @example
115 1111...111111 (30 bits total)
116 @end example
118 @noindent
119 @cindex two's complement
120 @minus{}1 is represented as 30 ones.  (This is called @dfn{two's
121 complement} notation.)
123   Subtracting 4 from @minus{}1 returns the negative integer @minus{}5.
124 In binary, the decimal integer 4 is 100.  Consequently,
125 @minus{}5 looks like this:
127 @example
128 1111...111011 (30 bits total)
129 @end example
131   In this implementation, the largest 30-bit binary integer is
132 536,870,911 in decimal.  In binary, it looks like this:
134 @example
135 0111...111111 (30 bits total)
136 @end example
138   Since the arithmetic functions do not check whether integers go
139 outside their range, when you add 1 to 536,870,911, the value is the
140 negative integer @minus{}536,870,912:
142 @example
143 (+ 1 536870911)
144      @result{} -536870912
145      @result{} 1000...000000 (30 bits total)
146 @end example
148   Many of the functions described in this chapter accept markers for
149 arguments in place of numbers.  (@xref{Markers}.)  Since the actual
150 arguments to such functions may be either numbers or markers, we often
151 give these arguments the name @var{number-or-marker}.  When the argument
152 value is a marker, its position value is used and its buffer is ignored.
154 @cindex largest Lisp integer
155 @cindex maximum Lisp integer
156 @defvar most-positive-fixnum
157 The value of this variable is the largest integer that Emacs Lisp can
158 handle.  Typical values are
159 @ifnottex
160 2**29 @minus{} 1
161 @end ifnottex
162 @tex
163 @math{2^{29}-1}
164 @end tex
165 on 32-bit and
166 @ifnottex
167 2**61 @minus{} 1
168 @end ifnottex
169 @tex
170 @math{2^{61}-1}
171 @end tex
172 on 64-bit platforms.
173 @end defvar
175 @cindex smallest Lisp integer
176 @cindex minimum Lisp integer
177 @defvar most-negative-fixnum
178 The value of this variable is the smallest integer that Emacs Lisp can
179 handle.  It is negative.  Typical values are
180 @ifnottex
181 @minus{}2**29
182 @end ifnottex
183 @tex
184 @math{-2^{29}}
185 @end tex
186 on 32-bit and
187 @ifnottex
188 @minus{}2**61
189 @end ifnottex
190 @tex
191 @math{-2^{61}}
192 @end tex
193 on 64-bit platforms.
194 @end defvar
196   In Emacs Lisp, text characters are represented by integers.  Any
197 integer between zero and the value of @code{(max-char)}, inclusive, is
198 considered to be valid as a character.  @xref{Character Codes}.
200 @node Float Basics
201 @section Floating-Point Basics
203 @cindex @acronym{IEEE} floating point
204   Floating-point numbers are useful for representing numbers that are
205 not integral.  The range of floating-point numbers is
206 the same as the range of the C data type @code{double} on the machine
207 you are using.  On all computers currently supported by Emacs, this is
208 double-precision @acronym{IEEE} floating point.
210   The read syntax for floating-point numbers requires either a decimal
211 point, an exponent, or both.  Optional signs (@samp{+} or @samp{-})
212 precede the number and its exponent.  For example, @samp{1500.0},
213 @samp{+15e2}, @samp{15.0e+2}, @samp{+1500000e-3}, and @samp{.15e4} are
214 five ways of writing a floating-point number whose value is 1500.
215 They are all equivalent.  Like Common Lisp, Emacs Lisp requires at
216 least one digit after any decimal point in a floating-point number;
217 @samp{1500.} is an integer, not a floating-point number.
219   Emacs Lisp treats @code{-0.0} as numerically equal to ordinary zero
220 with respect to @code{equal} and @code{=}.  This follows the
221 @acronym{IEEE} floating-point standard, which says @code{-0.0} and
222 @code{0.0} are numerically equal even though other operations can
223 distinguish them.
225 @cindex positive infinity
226 @cindex negative infinity
227 @cindex infinity
228 @cindex NaN
229   The @acronym{IEEE} floating-point standard supports positive
230 infinity and negative infinity as floating-point values.  It also
231 provides for a class of values called NaN, or ``not a number'';
232 numerical functions return such values in cases where there is no
233 correct answer.  For example, @code{(/ 0.0 0.0)} returns a NaN@.
234 Although NaN values carry a sign, for practical purposes there is no other
235 significant difference between different NaN values in Emacs Lisp.
237 Here are read syntaxes for these special floating-point values:
239 @table @asis
240 @item infinity
241 @samp{1.0e+INF} and @samp{-1.0e+INF}
242 @item not-a-number
243 @samp{0.0e+NaN} and @samp{-0.0e+NaN}
244 @end table
246   The following functions are specialized for handling floating-point
247 numbers:
249 @defun isnan x
250 This predicate returns @code{t} if its floating-point argument is a NaN,
251 @code{nil} otherwise.
252 @end defun
254 @defun frexp x
255 This function returns a cons cell @code{(@var{s} . @var{e})},
256 where @var{s} and @var{e} are respectively the significand and
257 exponent of the floating-point number @var{x}.
259 If @var{x} is finite, then @var{s} is a floating-point number between 0.5
260 (inclusive) and 1.0 (exclusive), @var{e} is an integer, and
261 @ifnottex
262 @var{x} = @var{s} * 2**@var{e}.
263 @end ifnottex
264 @tex
265 @math{x = s 2^e}.
266 @end tex
267 If @var{x} is zero or infinity, then @var{s} is the same as @var{x}.
268 If @var{x} is a NaN, then @var{s} is also a NaN@.
269 If @var{x} is zero, then @var{e} is 0.
270 @end defun
272 @defun ldexp s e
273 Given a numeric significand @var{s} and an integer exponent @var{e},
274 this function returns the floating point number
275 @ifnottex
276 @var{s} * 2**@var{e}.
277 @end ifnottex
278 @tex
279 @math{s 2^e}.
280 @end tex
281 @end defun
283 @defun copysign x1 x2
284 This function copies the sign of @var{x2} to the value of @var{x1},
285 and returns the result.  @var{x1} and @var{x2} must be floating point.
286 @end defun
288 @defun logb x
289 This function returns the binary exponent of @var{x}.  More
290 precisely, the value is the logarithm base 2 of @math{|x|}, rounded
291 down to an integer.
293 @example
294 (logb 10)
295      @result{} 3
296 (logb 10.0e20)
297      @result{} 69
298 @end example
299 @end defun
301 @node Predicates on Numbers
302 @section Type Predicates for Numbers
303 @cindex predicates for numbers
305   The functions in this section test for numbers, or for a specific
306 type of number.  The functions @code{integerp} and @code{floatp} can
307 take any type of Lisp object as argument (they would not be of much
308 use otherwise), but the @code{zerop} predicate requires a number as
309 its argument.  See also @code{integer-or-marker-p} and
310 @code{number-or-marker-p}, in @ref{Predicates on Markers}.
312 @defun floatp object
313 This predicate tests whether its argument is floating point
314 and returns @code{t} if so, @code{nil} otherwise.
315 @end defun
317 @defun integerp object
318 This predicate tests whether its argument is an integer, and returns
319 @code{t} if so, @code{nil} otherwise.
320 @end defun
322 @defun numberp object
323 This predicate tests whether its argument is a number (either integer or
324 floating point), and returns @code{t} if so, @code{nil} otherwise.
325 @end defun
327 @defun natnump object
328 @cindex natural numbers
329 This predicate (whose name comes from the phrase ``natural number'')
330 tests to see whether its argument is a nonnegative integer, and
331 returns @code{t} if so, @code{nil} otherwise.  0 is considered
332 non-negative.
334 @findex wholenump
335 @code{wholenump} is a synonym for @code{natnump}.
336 @end defun
338 @defun zerop number
339 This predicate tests whether its argument is zero, and returns @code{t}
340 if so, @code{nil} otherwise.  The argument must be a number.
342 @code{(zerop x)} is equivalent to @code{(= x 0)}.
343 @end defun
345 @node Comparison of Numbers
346 @section Comparison of Numbers
347 @cindex number comparison
348 @cindex comparing numbers
350   To test numbers for numerical equality, you should normally use
351 @code{=}, not @code{eq}.  There can be many distinct floating-point
352 objects with the same numeric value.  If you use @code{eq} to
353 compare them, then you test whether two values are the same
354 @emph{object}.  By contrast, @code{=} compares only the numeric values
355 of the objects.
357   In Emacs Lisp, each integer is a unique Lisp object.
358 Therefore, @code{eq} is equivalent to @code{=} where integers are
359 concerned.  It is sometimes convenient to use @code{eq} for comparing
360 an unknown value with an integer, because @code{eq} does not report an
361 error if the unknown value is not a number---it accepts arguments of
362 any type.  By contrast, @code{=} signals an error if the arguments are
363 not numbers or markers.  However, it is better programming practice to
364 use @code{=} if you can, even for comparing integers.
366   Sometimes it is useful to compare numbers with @code{equal}, which
367 treats two numbers as equal if they have the same data type (both
368 integers, or both floating point) and the same value.  By contrast,
369 @code{=} can treat an integer and a floating-point number as equal.
370 @xref{Equality Predicates}.
372   There is another wrinkle: because floating-point arithmetic is not
373 exact, it is often a bad idea to check for equality of floating-point
374 values.  Usually it is better to test for approximate equality.
375 Here's a function to do this:
377 @example
378 (defvar fuzz-factor 1.0e-6)
379 (defun approx-equal (x y)
380   (or (= x y)
381       (< (/ (abs (- x y))
382             (max (abs x) (abs y)))
383          fuzz-factor)))
384 @end example
386 @cindex CL note---integers vrs @code{eq}
387 @quotation
388 @b{Common Lisp note:} Comparing numbers in Common Lisp always requires
389 @code{=} because Common Lisp implements multi-word integers, and two
390 distinct integer objects can have the same numeric value.  Emacs Lisp
391 can have just one integer object for any given value because it has a
392 limited range of integers.
393 @end quotation
395 @defun = number-or-marker &rest number-or-markers
396 This function tests whether all its arguments are numerically equal,
397 and returns @code{t} if so, @code{nil} otherwise.
398 @end defun
400 @defun eql value1 value2
401 This function acts like @code{eq} except when both arguments are
402 numbers.  It compares numbers by type and numeric value, so that
403 @code{(eql 1.0 1)} returns @code{nil}, but @code{(eql 1.0 1.0)} and
404 @code{(eql 1 1)} both return @code{t}.
405 @end defun
407 @defun /= number-or-marker1 number-or-marker2
408 This function tests whether its arguments are numerically equal, and
409 returns @code{t} if they are not, and @code{nil} if they are.
410 @end defun
412 @defun <  number-or-marker &rest number-or-markers
413 This function tests whether each argument is strictly less than the
414 following argument.  It returns @code{t} if so, @code{nil} otherwise.
415 @end defun
417 @defun <= number-or-marker &rest number-or-markers
418 This function tests whether each argument is less than or equal to
419 the following argument.  It returns @code{t} if so, @code{nil} otherwise.
420 @end defun
422 @defun > number-or-marker &rest number-or-markers
423 This function tests whether each argument is strictly greater than
424 the following argument.  It returns @code{t} if so, @code{nil} otherwise.
425 @end defun
427 @defun >= number-or-marker &rest number-or-markers
428 This function tests whether each argument is greater than or equal to
429 the following argument.  It returns @code{t} if so, @code{nil} otherwise.
430 @end defun
432 @defun max number-or-marker &rest numbers-or-markers
433 This function returns the largest of its arguments.
435 @example
436 (max 20)
437      @result{} 20
438 (max 1 2.5)
439      @result{} 2.5
440 (max 1 3 2.5)
441      @result{} 3
442 @end example
443 @end defun
445 @defun min number-or-marker &rest numbers-or-markers
446 This function returns the smallest of its arguments.
448 @example
449 (min -4 1)
450      @result{} -4
451 @end example
452 @end defun
454 @defun abs number
455 This function returns the absolute value of @var{number}.
456 @end defun
458 @node Numeric Conversions
459 @section Numeric Conversions
460 @cindex rounding in conversions
461 @cindex number conversions
462 @cindex converting numbers
464 To convert an integer to floating point, use the function @code{float}.
466 @defun float number
467 This returns @var{number} converted to floating point.
468 If @var{number} is already floating point, @code{float} returns
469 it unchanged.
470 @end defun
472   There are four functions to convert floating-point numbers to
473 integers; they differ in how they round.  All accept an argument
474 @var{number} and an optional argument @var{divisor}.  Both arguments
475 may be integers or floating-point numbers.  @var{divisor} may also be
476 @code{nil}.  If @var{divisor} is @code{nil} or omitted, these
477 functions convert @var{number} to an integer, or return it unchanged
478 if it already is an integer.  If @var{divisor} is non-@code{nil}, they
479 divide @var{number} by @var{divisor} and convert the result to an
480 integer.  If @var{divisor} is zero (whether integer or
481 floating point), Emacs signals an @code{arith-error} error.
483 @defun truncate number &optional divisor
484 This returns @var{number}, converted to an integer by rounding towards
485 zero.
487 @example
488 (truncate 1.2)
489      @result{} 1
490 (truncate 1.7)
491      @result{} 1
492 (truncate -1.2)
493      @result{} -1
494 (truncate -1.7)
495      @result{} -1
496 @end example
497 @end defun
499 @defun floor number &optional divisor
500 This returns @var{number}, converted to an integer by rounding downward
501 (towards negative infinity).
503 If @var{divisor} is specified, this uses the kind of division
504 operation that corresponds to @code{mod}, rounding downward.
506 @example
507 (floor 1.2)
508      @result{} 1
509 (floor 1.7)
510      @result{} 1
511 (floor -1.2)
512      @result{} -2
513 (floor -1.7)
514      @result{} -2
515 (floor 5.99 3)
516      @result{} 1
517 @end example
518 @end defun
520 @defun ceiling number &optional divisor
521 This returns @var{number}, converted to an integer by rounding upward
522 (towards positive infinity).
524 @example
525 (ceiling 1.2)
526      @result{} 2
527 (ceiling 1.7)
528      @result{} 2
529 (ceiling -1.2)
530      @result{} -1
531 (ceiling -1.7)
532      @result{} -1
533 @end example
534 @end defun
536 @defun round number &optional divisor
537 This returns @var{number}, converted to an integer by rounding towards the
538 nearest integer.  Rounding a value equidistant between two integers
539 returns the even integer.
541 @example
542 (round 1.2)
543      @result{} 1
544 (round 1.7)
545      @result{} 2
546 (round -1.2)
547      @result{} -1
548 (round -1.7)
549      @result{} -2
550 @end example
551 @end defun
553 @node Arithmetic Operations
554 @section Arithmetic Operations
555 @cindex arithmetic operations
557   Emacs Lisp provides the traditional four arithmetic operations
558 (addition, subtraction, multiplication, and division), as well as
559 remainder and modulus functions, and functions to add or subtract 1.
560 Except for @code{%}, each of these functions accepts both integer and
561 floating-point arguments, and returns a floating-point number if any
562 argument is floating point.
564   Emacs Lisp arithmetic functions do not check for integer overflow.
565 Thus @code{(1+ 536870911)} may evaluate to
566 @minus{}536870912, depending on your hardware.
568 @defun 1+ number-or-marker
569 This function returns @var{number-or-marker} plus 1.
570 For example,
572 @example
573 (setq foo 4)
574      @result{} 4
575 (1+ foo)
576      @result{} 5
577 @end example
579 This function is not analogous to the C operator @code{++}---it does not
580 increment a variable.  It just computes a sum.  Thus, if we continue,
582 @example
584      @result{} 4
585 @end example
587 If you want to increment the variable, you must use @code{setq},
588 like this:
590 @example
591 (setq foo (1+ foo))
592      @result{} 5
593 @end example
594 @end defun
596 @defun 1- number-or-marker
597 This function returns @var{number-or-marker} minus 1.
598 @end defun
600 @defun + &rest numbers-or-markers
601 This function adds its arguments together.  When given no arguments,
602 @code{+} returns 0.
604 @example
606      @result{} 0
607 (+ 1)
608      @result{} 1
609 (+ 1 2 3 4)
610      @result{} 10
611 @end example
612 @end defun
614 @defun - &optional number-or-marker &rest more-numbers-or-markers
615 The @code{-} function serves two purposes: negation and subtraction.
616 When @code{-} has a single argument, the value is the negative of the
617 argument.  When there are multiple arguments, @code{-} subtracts each of
618 the @var{more-numbers-or-markers} from @var{number-or-marker},
619 cumulatively.  If there are no arguments, the result is 0.
621 @example
622 (- 10 1 2 3 4)
623      @result{} 0
624 (- 10)
625      @result{} -10
627      @result{} 0
628 @end example
629 @end defun
631 @defun * &rest numbers-or-markers
632 This function multiplies its arguments together, and returns the
633 product.  When given no arguments, @code{*} returns 1.
635 @example
637      @result{} 1
638 (* 1)
639      @result{} 1
640 (* 1 2 3 4)
641      @result{} 24
642 @end example
643 @end defun
645 @defun / number &rest divisors
646 With one or more @var{divisors}, this function divides @var{number}
647 by each divisor in @var{divisors} in turn, and returns the quotient.
648 With no @var{divisors}, this function returns 1/@var{number}, i.e.,
649 the multiplicative inverse of @var{number}.  Each argument may be a
650 number or a marker.
652 If all the arguments are integers, the result is an integer, obtained
653 by rounding the quotient towards zero after each division.
655 @example
656 @group
657 (/ 6 2)
658      @result{} 3
659 @end group
660 @group
661 (/ 5 2)
662      @result{} 2
663 @end group
664 @group
665 (/ 5.0 2)
666      @result{} 2.5
667 @end group
668 @group
669 (/ 5 2.0)
670      @result{} 2.5
671 @end group
672 @group
673 (/ 5.0 2.0)
674      @result{} 2.5
675 @end group
676 @group
677 (/ 4.0)
678      @result{} 0.25
679 @end group
680 @group
681 (/ 4)
682      @result{} 0
683 @end group
684 @group
685 (/ 25 3 2)
686      @result{} 4
687 @end group
688 @group
689 (/ -17 6)
690      @result{} -2
691 @end group
692 @end example
694 @cindex @code{arith-error} in division
695 If you divide an integer by the integer 0, Emacs signals an
696 @code{arith-error} error (@pxref{Errors}).  Floating-point division of
697 a nonzero number by zero yields either positive or negative infinity
698 (@pxref{Float Basics}).
699 @end defun
701 @defun % dividend divisor
702 @cindex remainder
703 This function returns the integer remainder after division of @var{dividend}
704 by @var{divisor}.  The arguments must be integers or markers.
706 For any two integers @var{dividend} and @var{divisor},
708 @example
709 @group
710 (+ (% @var{dividend} @var{divisor})
711    (* (/ @var{dividend} @var{divisor}) @var{divisor}))
712 @end group
713 @end example
715 @noindent
716 always equals @var{dividend} if @var{divisor} is nonzero.
718 @example
719 (% 9 4)
720      @result{} 1
721 (% -9 4)
722      @result{} -1
723 (% 9 -4)
724      @result{} 1
725 (% -9 -4)
726      @result{} -1
727 @end example
728 @end defun
730 @defun mod dividend divisor
731 @cindex modulus
732 This function returns the value of @var{dividend} modulo @var{divisor};
733 in other words, the remainder after division of @var{dividend}
734 by @var{divisor}, but with the same sign as @var{divisor}.
735 The arguments must be numbers or markers.
737 Unlike @code{%}, @code{mod} permits floating-point arguments; it
738 rounds the quotient downward (towards minus infinity) to an integer,
739 and uses that quotient to compute the remainder.
741 If @var{divisor} is zero, @code{mod} signals an @code{arith-error}
742 error if both arguments are integers, and returns a NaN otherwise.
744 @example
745 @group
746 (mod 9 4)
747      @result{} 1
748 @end group
749 @group
750 (mod -9 4)
751      @result{} 3
752 @end group
753 @group
754 (mod 9 -4)
755      @result{} -3
756 @end group
757 @group
758 (mod -9 -4)
759      @result{} -1
760 @end group
761 @group
762 (mod 5.5 2.5)
763      @result{} .5
764 @end group
765 @end example
767 For any two numbers @var{dividend} and @var{divisor},
769 @example
770 @group
771 (+ (mod @var{dividend} @var{divisor})
772    (* (floor @var{dividend} @var{divisor}) @var{divisor}))
773 @end group
774 @end example
776 @noindent
777 always equals @var{dividend}, subject to rounding error if either
778 argument is floating point and to an @code{arith-error} if @var{dividend} is an
779 integer and @var{divisor} is 0.  For @code{floor}, see @ref{Numeric
780 Conversions}.
781 @end defun
783 @node Rounding Operations
784 @section Rounding Operations
785 @cindex rounding without conversion
787 The functions @code{ffloor}, @code{fceiling}, @code{fround}, and
788 @code{ftruncate} take a floating-point argument and return a floating-point
789 result whose value is a nearby integer.  @code{ffloor} returns the
790 nearest integer below; @code{fceiling}, the nearest integer above;
791 @code{ftruncate}, the nearest integer in the direction towards zero;
792 @code{fround}, the nearest integer.
794 @defun ffloor float
795 This function rounds @var{float} to the next lower integral value, and
796 returns that value as a floating-point number.
797 @end defun
799 @defun fceiling float
800 This function rounds @var{float} to the next higher integral value, and
801 returns that value as a floating-point number.
802 @end defun
804 @defun ftruncate float
805 This function rounds @var{float} towards zero to an integral value, and
806 returns that value as a floating-point number.
807 @end defun
809 @defun fround float
810 This function rounds @var{float} to the nearest integral value,
811 and returns that value as a floating-point number.
812 Rounding a value equidistant between two integers returns the even integer.
813 @end defun
815 @node Bitwise Operations
816 @section Bitwise Operations on Integers
817 @cindex bitwise arithmetic
818 @cindex logical arithmetic
820   In a computer, an integer is represented as a binary number, a
821 sequence of @dfn{bits} (digits which are either zero or one).  A bitwise
822 operation acts on the individual bits of such a sequence.  For example,
823 @dfn{shifting} moves the whole sequence left or right one or more places,
824 reproducing the same pattern moved over.
826   The bitwise operations in Emacs Lisp apply only to integers.
828 @defun lsh integer1 count
829 @cindex logical shift
830 @code{lsh}, which is an abbreviation for @dfn{logical shift}, shifts the
831 bits in @var{integer1} to the left @var{count} places, or to the right
832 if @var{count} is negative, bringing zeros into the vacated bits.  If
833 @var{count} is negative, @code{lsh} shifts zeros into the leftmost
834 (most-significant) bit, producing a positive result even if
835 @var{integer1} is negative.  Contrast this with @code{ash}, below.
837 Here are two examples of @code{lsh}, shifting a pattern of bits one
838 place to the left.  We show only the low-order eight bits of the binary
839 pattern; the rest are all zero.
841 @example
842 @group
843 (lsh 5 1)
844      @result{} 10
845 ;; @r{Decimal 5 becomes decimal 10.}
846 00000101 @result{} 00001010
848 (lsh 7 1)
849      @result{} 14
850 ;; @r{Decimal 7 becomes decimal 14.}
851 00000111 @result{} 00001110
852 @end group
853 @end example
855 @noindent
856 As the examples illustrate, shifting the pattern of bits one place to
857 the left produces a number that is twice the value of the previous
858 number.
860 Shifting a pattern of bits two places to the left produces results
861 like this (with 8-bit binary numbers):
863 @example
864 @group
865 (lsh 3 2)
866      @result{} 12
867 ;; @r{Decimal 3 becomes decimal 12.}
868 00000011 @result{} 00001100
869 @end group
870 @end example
872 On the other hand, shifting one place to the right looks like this:
874 @example
875 @group
876 (lsh 6 -1)
877      @result{} 3
878 ;; @r{Decimal 6 becomes decimal 3.}
879 00000110 @result{} 00000011
880 @end group
882 @group
883 (lsh 5 -1)
884      @result{} 2
885 ;; @r{Decimal 5 becomes decimal 2.}
886 00000101 @result{} 00000010
887 @end group
888 @end example
890 @noindent
891 As the example illustrates, shifting one place to the right divides the
892 value of a positive integer by two, rounding downward.
894 The function @code{lsh}, like all Emacs Lisp arithmetic functions, does
895 not check for overflow, so shifting left can discard significant bits
896 and change the sign of the number.  For example, left shifting
897 536,870,911 produces @minus{}2 in the 30-bit implementation:
899 @example
900 (lsh 536870911 1)          ; @r{left shift}
901      @result{} -2
902 @end example
904 In binary, the argument looks like this:
906 @example
907 @group
908 ;; @r{Decimal 536,870,911}
909 0111...111111 (30 bits total)
910 @end group
911 @end example
913 @noindent
914 which becomes the following when left shifted:
916 @example
917 @group
918 ;; @r{Decimal @minus{}2}
919 1111...111110 (30 bits total)
920 @end group
921 @end example
922 @end defun
924 @defun ash integer1 count
925 @cindex arithmetic shift
926 @code{ash} (@dfn{arithmetic shift}) shifts the bits in @var{integer1}
927 to the left @var{count} places, or to the right if @var{count}
928 is negative.
930 @code{ash} gives the same results as @code{lsh} except when
931 @var{integer1} and @var{count} are both negative.  In that case,
932 @code{ash} puts ones in the empty bit positions on the left, while
933 @code{lsh} puts zeros in those bit positions.
935 Thus, with @code{ash}, shifting the pattern of bits one place to the right
936 looks like this:
938 @example
939 @group
940 (ash -6 -1) @result{} -3
941 ;; @r{Decimal @minus{}6 becomes decimal @minus{}3.}
942 1111...111010 (30 bits total)
943      @result{}
944 1111...111101 (30 bits total)
945 @end group
946 @end example
948 In contrast, shifting the pattern of bits one place to the right with
949 @code{lsh} looks like this:
951 @example
952 @group
953 (lsh -6 -1) @result{} 536870909
954 ;; @r{Decimal @minus{}6 becomes decimal 536,870,909.}
955 1111...111010 (30 bits total)
956      @result{}
957 0111...111101 (30 bits total)
958 @end group
959 @end example
961 Here are other examples:
963 @c !!! Check if lined up in smallbook format!  XDVI shows problem
964 @c     with smallbook but not with regular book! --rjc 16mar92
965 @smallexample
966 @group
967                    ;  @r{       30-bit binary values}
969 (lsh 5 2)          ;   5  =  @r{0000...000101}
970      @result{} 20         ;      =  @r{0000...010100}
971 @end group
972 @group
973 (ash 5 2)
974      @result{} 20
975 (lsh -5 2)         ;  -5  =  @r{1111...111011}
976      @result{} -20        ;      =  @r{1111...101100}
977 (ash -5 2)
978      @result{} -20
979 @end group
980 @group
981 (lsh 5 -2)         ;   5  =  @r{0000...000101}
982      @result{} 1          ;      =  @r{0000...000001}
983 @end group
984 @group
985 (ash 5 -2)
986      @result{} 1
987 @end group
988 @group
989 (lsh -5 -2)        ;  -5  =  @r{1111...111011}
990      @result{} 268435454
991                    ;      =  @r{0011...111110}
992 @end group
993 @group
994 (ash -5 -2)        ;  -5  =  @r{1111...111011}
995      @result{} -2         ;      =  @r{1111...111110}
996 @end group
997 @end smallexample
998 @end defun
1000 @defun logand &rest ints-or-markers
1001 This function returns the bitwise AND of the arguments: the @var{n}th
1002 bit is 1 in the result if, and only if, the @var{n}th bit is 1 in all
1003 the arguments.
1005 For example, using 4-bit binary numbers, the bitwise AND of 13 and
1006 12 is 12: 1101 combined with 1100 produces 1100.
1007 In both the binary numbers, the leftmost two bits are both 1
1008 so the leftmost two bits of the returned value are both 1.
1009 However, for the rightmost two bits, each is 0 in at least one of
1010 the arguments, so the rightmost two bits of the returned value are both 0.
1012 @noindent
1013 Therefore,
1015 @example
1016 @group
1017 (logand 13 12)
1018      @result{} 12
1019 @end group
1020 @end example
1022 If @code{logand} is not passed any argument, it returns a value of
1023 @minus{}1.  This number is an identity element for @code{logand}
1024 because its binary representation consists entirely of ones.  If
1025 @code{logand} is passed just one argument, it returns that argument.
1027 @smallexample
1028 @group
1029                    ; @r{       30-bit binary values}
1031 (logand 14 13)     ; 14  =  @r{0000...001110}
1032                    ; 13  =  @r{0000...001101}
1033      @result{} 12         ; 12  =  @r{0000...001100}
1034 @end group
1036 @group
1037 (logand 14 13 4)   ; 14  =  @r{0000...001110}
1038                    ; 13  =  @r{0000...001101}
1039                    ;  4  =  @r{0000...000100}
1040      @result{} 4          ;  4  =  @r{0000...000100}
1041 @end group
1043 @group
1044 (logand)
1045      @result{} -1         ; -1  =  @r{1111...111111}
1046 @end group
1047 @end smallexample
1048 @end defun
1050 @defun logior &rest ints-or-markers
1051 This function returns the bitwise inclusive OR of its arguments: the @var{n}th
1052 bit is 1 in the result if, and only if, the @var{n}th bit is 1 in at
1053 least one of the arguments.  If there are no arguments, the result is 0,
1054 which is an identity element for this operation.  If @code{logior} is
1055 passed just one argument, it returns that argument.
1057 @smallexample
1058 @group
1059                    ; @r{       30-bit binary values}
1061 (logior 12 5)      ; 12  =  @r{0000...001100}
1062                    ;  5  =  @r{0000...000101}
1063      @result{} 13         ; 13  =  @r{0000...001101}
1064 @end group
1066 @group
1067 (logior 12 5 7)    ; 12  =  @r{0000...001100}
1068                    ;  5  =  @r{0000...000101}
1069                    ;  7  =  @r{0000...000111}
1070      @result{} 15         ; 15  =  @r{0000...001111}
1071 @end group
1072 @end smallexample
1073 @end defun
1075 @defun logxor &rest ints-or-markers
1076 This function returns the bitwise exclusive OR of its arguments: the
1077 @var{n}th bit is 1 in the result if, and only if, the @var{n}th bit is
1078 1 in an odd number of the arguments.  If there are no arguments, the
1079 result is 0, which is an identity element for this operation.  If
1080 @code{logxor} is passed just one argument, it returns that argument.
1082 @smallexample
1083 @group
1084                    ; @r{       30-bit binary values}
1086 (logxor 12 5)      ; 12  =  @r{0000...001100}
1087                    ;  5  =  @r{0000...000101}
1088      @result{} 9          ;  9  =  @r{0000...001001}
1089 @end group
1091 @group
1092 (logxor 12 5 7)    ; 12  =  @r{0000...001100}
1093                    ;  5  =  @r{0000...000101}
1094                    ;  7  =  @r{0000...000111}
1095      @result{} 14         ; 14  =  @r{0000...001110}
1096 @end group
1097 @end smallexample
1098 @end defun
1100 @defun lognot integer
1101 This function returns the bitwise complement of its argument: the @var{n}th
1102 bit is one in the result if, and only if, the @var{n}th bit is zero in
1103 @var{integer}, and vice-versa.
1105 @example
1106 (lognot 5)
1107      @result{} -6
1108 ;;  5  =  @r{0000...000101} (30 bits total)
1109 ;; @r{becomes}
1110 ;; -6  =  @r{1111...111010} (30 bits total)
1111 @end example
1112 @end defun
1114 @cindex popcount
1115 @cindex Hamming weight
1116 @cindex counting set bits
1117 @defun logcount integer
1118 This function returns the @dfn{Hamming weight} of @var{integer}: the
1119 number of ones in the binary representation of @var{integer}.
1120 If @var{integer} is negative, it returns the number of zero bits in
1121 its two's complement binary representation.  The result is always
1122 nonnegative.
1124 @example
1125 (logcount 43)     ; 43 = #b101011
1126      @result{} 4
1127 (logcount -43)    ; -43 = #b111...1010101
1128      @result{} 3
1129 @end example
1130 @end defun
1132 @node Math Functions
1133 @section Standard Mathematical Functions
1134 @cindex transcendental functions
1135 @cindex mathematical functions
1136 @cindex floating-point functions
1138   These mathematical functions allow integers as well as floating-point
1139 numbers as arguments.
1141 @defun sin arg
1142 @defunx cos arg
1143 @defunx tan arg
1144 These are the basic trigonometric functions, with argument @var{arg}
1145 measured in radians.
1146 @end defun
1148 @defun asin arg
1149 The value of @code{(asin @var{arg})} is a number between
1150 @ifnottex
1151 @minus{}pi/2
1152 @end ifnottex
1153 @tex
1154 @math{-\pi/2}
1155 @end tex
1157 @ifnottex
1158 pi/2
1159 @end ifnottex
1160 @tex
1161 @math{\pi/2}
1162 @end tex
1163 (inclusive) whose sine is @var{arg}.  If @var{arg} is out of range
1164 (outside [@minus{}1, 1]), @code{asin} returns a NaN.
1165 @end defun
1167 @defun acos arg
1168 The value of @code{(acos @var{arg})} is a number between 0 and
1169 @ifnottex
1171 @end ifnottex
1172 @tex
1173 @math{\pi}
1174 @end tex
1175 (inclusive) whose cosine is @var{arg}.  If @var{arg} is out of range
1176 (outside [@minus{}1, 1]), @code{acos} returns a NaN.
1177 @end defun
1179 @defun atan y &optional x
1180 The value of @code{(atan @var{y})} is a number between
1181 @ifnottex
1182 @minus{}pi/2
1183 @end ifnottex
1184 @tex
1185 @math{-\pi/2}
1186 @end tex
1188 @ifnottex
1189 pi/2
1190 @end ifnottex
1191 @tex
1192 @math{\pi/2}
1193 @end tex
1194 (exclusive) whose tangent is @var{y}.  If the optional second
1195 argument @var{x} is given, the value of @code{(atan y x)} is the
1196 angle in radians between the vector @code{[@var{x}, @var{y}]} and the
1197 @code{X} axis.
1198 @end defun
1200 @defun exp arg
1201 This is the exponential function; it returns @math{e} to the power
1202 @var{arg}.
1203 @end defun
1205 @defun log arg &optional base
1206 This function returns the logarithm of @var{arg}, with base
1207 @var{base}.  If you don't specify @var{base}, the natural base
1208 @math{e} is used.  If @var{arg} or @var{base} is negative, @code{log}
1209 returns a NaN.
1210 @end defun
1212 @defun expt x y
1213 This function returns @var{x} raised to power @var{y}.  If both
1214 arguments are integers and @var{y} is positive, the result is an
1215 integer; in this case, overflow causes truncation, so watch out.
1216 If @var{x} is a finite negative number and @var{y} is a finite
1217 non-integer, @code{expt} returns a NaN.
1218 @end defun
1220 @defun sqrt arg
1221 This returns the square root of @var{arg}.  If @var{arg} is finite
1222 and less than zero, @code{sqrt} returns a NaN.
1223 @end defun
1225 In addition, Emacs defines the following common mathematical
1226 constants:
1228 @defvar float-e
1229 The mathematical constant @math{e} (2.71828@dots{}).
1230 @end defvar
1232 @defvar float-pi
1233 The mathematical constant @math{pi} (3.14159@dots{}).
1234 @end defvar
1236 @node Random Numbers
1237 @section Random Numbers
1238 @cindex random numbers
1240   A deterministic computer program cannot generate true random
1241 numbers.  For most purposes, @dfn{pseudo-random numbers} suffice.  A
1242 series of pseudo-random numbers is generated in a deterministic
1243 fashion.  The numbers are not truly random, but they have certain
1244 properties that mimic a random series.  For example, all possible
1245 values occur equally often in a pseudo-random series.
1247 @cindex seed, for random number generation
1248   Pseudo-random numbers are generated from a @dfn{seed value}.  Starting from
1249 any given seed, the @code{random} function always generates the same
1250 sequence of numbers.  By default, Emacs initializes the random seed at
1251 startup, in such a way that the sequence of values of @code{random}
1252 (with overwhelming likelihood) differs in each Emacs run.
1254   Sometimes you want the random number sequence to be repeatable.  For
1255 example, when debugging a program whose behavior depends on the random
1256 number sequence, it is helpful to get the same behavior in each
1257 program run.  To make the sequence repeat, execute @code{(random "")}.
1258 This sets the seed to a constant value for your particular Emacs
1259 executable (though it may differ for other Emacs builds).  You can use
1260 other strings to choose various seed values.
1262 @defun random &optional limit
1263 This function returns a pseudo-random integer.  Repeated calls return a
1264 series of pseudo-random integers.
1266 If @var{limit} is a positive integer, the value is chosen to be
1267 nonnegative and less than @var{limit}.  Otherwise, the value might be
1268 any integer representable in Lisp, i.e., an integer between
1269 @code{most-negative-fixnum} and @code{most-positive-fixnum}
1270 (@pxref{Integer Basics}).
1272 If @var{limit} is @code{t}, it means to choose a new seed as if Emacs
1273 were restarting, typically from the system entropy.  On systems
1274 lacking entropy pools, choose the seed from less-random volatile data
1275 such as the current time.
1277 If @var{limit} is a string, it means to choose a new seed based on the
1278 string's contents.
1280 @end defun