GNU Emacs
ELisp
Numbers
ELisp 30.2 elisp

Numbers

GNU Emacs supports two numeric data types: integers and floating-point numbers. Integers are whole numbers such as −3, 0, 7, 13, and 511. Floating-point numbers are numbers with fractional parts, such as −4.5, 0.0, and 2.71828. They can also be expressed in exponential notation: 1.5e2 is the same as 150.0; here, e2 stands for ten to the second power, and that is multiplied by 1.5. Integer computations are exact. Floating-point computations often involve rounding errors, as the numbers have a fixed amount of precision.

Integer Basics

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

1               ; The integer 1.
 1.              ; The integer 1.
+1               ; Also the integer 1.
-1               ; The integer −1.
 0               ; The integer 0.
-0               ; The integer 0.

The syntax for integers in bases other than 10 consists of # followed by a radix indication followed by one or more digits. The radix indications are b for binary, o for octal, x for hex, and RADIXr for radix radix. Thus, #bINTEGER reads integer in binary, and #RADIXrINTEGER reads integer in radix radix. Allowed values of radix run from 2 to 36, and allowed digits are the first radix characters taken from 09, AZ. Letter case is ignored and there is no initial sign or final period. For example:

#b101100 => 44
#o54 => 44
#x2c => 44
#24r1k => 44

To understand how various functions work on integers, especially the bitwise operators (Bitwise Operations), it is often helpful to view the numbers in their binary form. In binary, the decimal integer 5 looks like this:

...000101

(The ellipsis ... stands for a conceptually infinite number of bits that match the leading bit; here, an infinite number of 0 bits. Later examples also use this ... notation.) The integer −1 looks like this:

...111111

−1 is represented as all ones. (This is called two's complement notation.) Subtracting 4 from −1 returns the negative integer −5. In binary, the decimal integer 4 is 100. Consequently, −5 looks like this:

...111011

Many of the functions described in this chapter accept markers for arguments in place of numbers. (Markers.) Since the actual arguments to such functions may be either numbers or markers, we often give these arguments the name number-or-marker. When the argument value is a marker, its position value is used and its buffer is ignored. In Emacs Lisp, text characters are represented by integers. Any integer between zero and the value of (max-char), inclusive, is considered to be valid as a character. Character Codes. Integers in Emacs Lisp are not limited to the machine word size. Under the hood, though, there are two kinds of integers: smaller ones, called fixnums, and larger ones, called bignums. Although Emacs Lisp code ordinarily should not depend on whether an integer is a fixnum or a bignum, older Emacs versions support only fixnums, some functions in Emacs still accept only fixnums, and older Emacs Lisp code may have trouble when given bignums. For example, while older Emacs Lisp code could safely compare integers for numeric equality with eq, the presence of bignums means that equality predicates like eql and = should now be used to compare integers. The range of values for bignums is limited by the amount of main memory, by machine characteristics such as the size of the word used to represent a bignum's exponent, and by the integer-width variable. These limits are typically much more generous than the limits for fixnums. A bignum is never numerically equal to a fixnum; Emacs always represents an integer in fixnum range as a fixnum, not a bignum. The range of values for a fixnum depends on the machine. The minimum range is −536,870,912 to 536,870,911 (30 bits; i.e., −2**29 to 2**29 − 1), but many machines provide a wider range.

most-positive-fixnum
The value of this variable is the greatest "small" integer that Emacs Lisp can handle. Typical values are 2**29 − 1 on 32-bit and 2**61 − 1 on 64-bit platforms.
most-negative-fixnum
The value of this variable is the numerically least "small" integer that Emacs Lisp can handle. It is negative. Typical values are −2**29 on 32-bit and −2**61 on 64-bit platforms.
integer-width
The value of this variable is a nonnegative integer that controls whether Emacs signals a range error when a large integer would be calculated. Integers with absolute values less than 2**/n/, where n is this variable's value, do not signal a range error. Attempts to create larger integers typically signal a range error, although there might be no signal if a larger integer can be created cheaply. Setting this variable to a large number can be costly if a computation creates huge integers.

Floating-Point Basics

Floating-point numbers are useful for representing numbers that are not integral. The range of floating-point numbers is the same as the range of the C data type double on the machine you are using. On almost all computers supported by Emacs, this is IEEE binary64 floating point format, which is standardized by https://standards.ieee.org/standard/754-2019.html and is discussed further in David Goldberg's paper "What Every Computer Scientist Should Know About Floating-Point Arithmetic". On modern platforms, floating-point operations follow the IEEE-754 standard closely; however, results are not always rounded correctly on some systems, notably 32-bit x86. On some old computer systems, Emacs may not use IEEE floating-point. We know of one such system on which Emacs runs correctly, but does not follow IEEE-754: the VAX running NetBSD using GCC 10.4.0, where the VAX D_Floating format is used instead. IBM System/370-derived mainframes and their XL/C compiler are also capable of utilizing a hexadecimal floating point format, but Emacs has not yet been built in such a configuration. The read syntax for floating-point numbers requires either a decimal point, an exponent, or both. Optional signs (+ or -) precede the number and its exponent. For example, 1500.0, +15e2, 15.0e+2, +1500000e-3, and .15e4 are five ways of writing a floating-point number whose value is 1500. They are all equivalent. Like Common Lisp, Emacs Lisp requires at least one digit after a decimal point in a floating-point number that does not have an exponent; 1500. is an integer, not a floating-point number. Emacs Lisp treats -0.0 as numerically equal to ordinary zero with respect to numeric comparisons like =. This follows the IEEE floating-point standard, which says -0.0 and 0.0 are numerically equal even though other operations can distinguish them. The IEEE floating-point standard supports 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, (/ 0.0 0.0) returns a NaN. A NaN is never numerically equal to any value, not even to itself. NaNs carry a sign and a significand, and non-numeric functions treat two NaNs as equal when their signs and significands agree. Significands of NaNs are machine-dependent, as are the digits in their string representation. When NaNs and signed zeros are involved, non-numeric functions like eql, equal, sxhash-eql, sxhash-equal and gethash determine whether values are indistinguishable, not whether they are numerically equal. For example, when x and y are the same NaN, (equal x y) returns t whereas ( x y)= uses numeric comparison and returns nil; conversely, (equal 0.0 -0.0) returns nil whereas ( 0.0 -0.0)= returns t. Here are read syntaxes for these special floating-point values:

infinity
1.0e+INF and -1.0e+INF
not-a-number
0.0e+NaN and -0.0e+NaN

Infinities and NaNs are not available on legacy systems that lack IEEE floating-point arithmetic. On a circa 1980 VAX, for example, Lisp reads 1.0e+INF as a large but finite floating-point number, and 0.0e+NaN as some other non-numeric Lisp object that provokes an error if used numerically. The following functions are specialized for handling floating-point numbers:

isnan
This predicate returns t if its floating-point argument is a NaN, nil otherwise.
frexp
This function returns a cons cell (S . E), where s and e are respectively the significand and exponent of the floating-point number x. If x is finite, then s is a floating-point number between 0.5 (inclusive) and 1.0 (exclusive), e is an integer, and x = s * 2**/e/. If x is zero or infinity, then s is the same as x. If x is a NaN, then s is also a NaN. If x is zero, then e is 0.
ldexp
Given a numeric significand s and an integer exponent e, this function returns the floating point number s * 2**/e/.
copysign
This function copies the sign of x2 to the value of x1, and returns the result. x1 and x2 must be floating point.
logb
This function returns the binary exponent of x. More precisely, if x is finite and nonzero, the value is the logarithm base 2 of |x|, rounded down to an integer. If x is zero or infinite, the value is infinity; if x is a NaN, the value is a NaN.
(logb 10)
     => 3
(logb 10.0e20)
     => 69
(logb 0)
     => -1.0e+INF

Type Predicates for Numbers

The functions in this section test for numbers, or for a specific type of number. The functions integerp and floatp can take any type of Lisp object as argument (they would not be of much use otherwise), but the zerop predicate requires a number as its argument. See also integer-or-marker-p and number-or-marker-p, in Predicates on Markers.

bignump
This predicate tests whether its argument is a large integer, and returns t if so, nil otherwise. Unlike small integers, large integers can be = or eql even if they are not eq.
fixnump
This predicate tests whether its argument is a small integer, and returns t if so, nil otherwise. Small integers can be compared with eq.
floatp
This predicate tests whether its argument is floating point and returns t if so, nil otherwise.
integerp
This predicate tests whether its argument is an integer, and returns t if so, nil otherwise.
numberp
This predicate tests whether its argument is a number (either integer or floating point), and returns t if so, nil otherwise.
natnump
This predicate (whose name comes from the phrase "natural number") tests to see whether its argument is a nonnegative integer, and returns t if so, nil otherwise. 0 is considered non-negative. wholenump is a synonym for natnump.
zerop
This predicate tests whether its argument is zero, and returns t if so, nil otherwise. The argument must be a number. (zerop x) is equivalent to ( x 0)=.

Comparison of Numbers

To test numbers for numerical equality, you should normally use = instead of non-numeric comparison predicates like eq, eql and equal. Distinct floating-point and large integer objects can be numerically equal. If you use eq to compare them, you test whether they are the same object; if you use eql or equal, you test whether their values are indistinguishable. In contrast, = uses numeric comparison, and sometimes returns t when a non-numeric comparison would return nil and vice versa. Float Basics. In Emacs Lisp, if two fixnums are numerically equal, they are the same Lisp object. That is, eq is equivalent to = on fixnums. It is sometimes convenient to use eq for comparing an unknown value with a fixnum, because eq does not report an error if the unknown value is not a number—it accepts arguments of any type. By contrast, = signals an error if the arguments are not numbers or markers. However, it is better programming practice to use = if you can, even for comparing integers. Sometimes it is useful to compare numbers with eql or equal, which treat two numbers as equal if they have the same data type (both integers, or both floating point) and the same value. By contrast, = can treat an integer and a floating-point number as equal. Equality Predicates. There is another wrinkle: because floating-point arithmetic is not exact, it is often a bad idea to check for equality of floating-point values. Usually it is better to test for approximate equality. Here's a function to do this:

(defvar fuzz-factor 1.0e-6)
(defun approx-equal (x y)
  (or (= x y)
      (< (/ (abs (- x y))
            (max (abs x) (abs y)))
         fuzz-factor)))
=
This function tests whether all its arguments are numerically equal, and returns t if so, nil otherwise.
eql
This function acts like eq except when both arguments are numbers. It compares numbers by type and numeric value, so that (eql 1.0 1) returns nil, but (eql 1.0 1.0) and (eql 1 1) both return t. This can be used to compare large integers as well as small ones. Floating-point values with the same sign, exponent and fraction are eql. This differs from numeric comparison: (eql 0.0 -0.0) returns nil and (eql 0.0e+NaN 0.0e+NaN) returns t, whereas = does the opposite.
/=
This function tests whether its arguments are numerically equal, and returns t if they are not, and nil if they are.
<
This function tests whether each argument is strictly less than the following argument. It returns t if so, nil otherwise.
<=
This function tests whether each argument is less than or equal to the following argument. It returns t if so, nil otherwise.
>
This function tests whether each argument is strictly greater than the following argument. It returns t if so, nil otherwise.
>=
This function tests whether each argument is greater than or equal to the following argument. It returns t if so, nil otherwise.
max
This function returns the largest of its arguments.
(max 20)
     => 20
(max 1 2.5)
     => 2.5
(max 1 3 2.5)
     => 3
min
This function returns the smallest of its arguments.
(min -4 1)
     => -4
abs
This function returns the absolute value of number.

Numeric Conversions

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

float
This returns number converted to floating point. If number is already floating point, float returns it unchanged.

There are four functions to convert floating-point numbers to integers; they differ in how they round. All accept an argument number and an optional argument divisor. Both arguments may be integers or floating-point numbers. divisor may also be nil. If divisor is nil or omitted, these functions convert number to an integer, or return it unchanged if it already is an integer. If divisor is non-nil, they divide number by divisor and convert the result to an integer. If divisor is zero (whether integer or floating point), Emacs signals an arith-error error.

truncate
This returns number, converted to an integer by rounding towards zero.
(truncate 1.2)
     => 1
(truncate 1.7)
     => 1
(truncate -1.2)
     => -1
(truncate -1.7)
     => -1
floor
This returns number, converted to an integer by rounding downward (towards negative infinity). If divisor is specified, this uses the kind of division operation that corresponds to mod, rounding downward.
(floor 1.2)
     => 1
(floor 1.7)
     => 1
(floor -1.2)
     => -2
(floor -1.7)
     => -2
(floor 5.99 3)
     => 1
ceiling
This returns number, converted to an integer by rounding upward (towards positive infinity).
(ceiling 1.2)
     => 2
(ceiling 1.7)
     => 2
(ceiling -1.2)
     => -1
(ceiling -1.7)
     => -1
round
This returns number, converted to an integer by rounding towards the nearest integer. Rounding a value equidistant between two integers returns the even integer.
(round 1.2)
     => 1
(round 1.7)
     => 2
(round -1.2)
     => -1
(round -1.7)
     => -2

Arithmetic Operations

Emacs Lisp provides the traditional four arithmetic operations (addition, subtraction, multiplication, and division), as well as remainder and modulus functions, and functions to add or subtract 1. Except for %, each of these functions accepts both integer and floating-point arguments, and returns a floating-point number if any argument is floating point.

1+
This function returns number-or-marker plus 1. For example,
(setq foo 4)
     => 4
(1+ foo)
     => 5

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

foo
     => 4

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

(setq foo (1+ foo))
     => 5
1-
This function returns number-or-marker minus 1.
+
This function adds its arguments together. When given no arguments, + returns 0.
(+)
     => 0
(+ 1)
     => 1
(+ 1 2 3 4)
     => 10
-
The - function serves two purposes: negation and subtraction. When - has a single argument, the value is the negative of the argument. When there are multiple arguments, - subtracts each of the more-numbers-or-markers from number-or-marker, cumulatively. If there are no arguments, the result is 0.
(- 10 1 2 3 4)
     => 0
(- 10)
     => -10
(-)
     => 0
*
This function multiplies its arguments together, and returns the product. When given no arguments, * returns 1.
(*)
     => 1
(* 1)
     => 1
(* 1 2 3 4)
     => 24
/
With one or more divisors, this function divides number by each divisor in divisors in turn, and returns the quotient. With no divisors, this function returns 1//number/, i.e., the multiplicative inverse of number. Each argument may be a number or a marker. If all the arguments are integers, the result is an integer, obtained by rounding the quotient towards zero after each division.
(/ 6 2)
     => 3
(/ 5 2)
     => 2
(/ 5.0 2)
     => 2.5
(/ 5 2.0)
     => 2.5
(/ 5.0 2.0)
     => 2.5
(/ 4.0)
     => 0.25
(/ 4)
     => 0
(/ 25 3 2)
     => 4
(/ -17 6)
     => -2

If you divide an integer by the integer 0, Emacs signals an arith-error error (Errors). On systems using IEEE-754 floating-point, floating-point division of a nonzero number by zero yields either positive or negative infinity (Float Basics); otherwise, an arith-error is signaled as usual.

%
This function returns the integer remainder after division of dividend by divisor. The arguments must be integers or markers. For any two integers dividend and divisor,
(+ (% DIVIDEND DIVISOR)
   (* (/ DIVIDEND DIVISOR) DIVISOR))

always equals dividend if divisor is nonzero.

(% 9 4)
     => 1
(% -9 4)
     => -1
(% 9 -4)
     => 1
(% -9 -4)
     => -1
mod
This function returns the value of dividend modulo divisor; in other words, the remainder after division of dividend by divisor, but with the same sign as divisor. The arguments must be numbers or markers. Unlike %, mod permits floating-point arguments; it rounds the quotient downward (towards minus infinity) to an integer, and uses that quotient to compute the remainder. If divisor is zero, mod signals an arith-error error if both arguments are integers, and returns a NaN otherwise.
(mod 9 4)
     => 1
(mod -9 4)
     => 3
(mod 9 -4)
     => -3
(mod -9 -4)
     => -1
(mod 5.5 2.5)
     => .5

For any two numbers dividend and divisor,

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

always equals dividend, subject to rounding error if either argument is floating point and to an arith-error if dividend is an integer and divisor is 0. For floor, see Numeric Conversions.

Rounding Operations

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

ffloor
This function rounds float to the next lower integral value, and returns that value as a floating-point number.
fceiling
This function rounds float to the next higher integral value, and returns that value as a floating-point number.
ftruncate
This function rounds float towards zero to an integral value, and returns that value as a floating-point number.
fround
This function rounds float to the nearest integral value, and returns that value as a floating-point number. Rounding a value equidistant between two integers returns the even integer.

Bitwise Operations on Integers

In a computer, an integer is represented as a binary number, a sequence of bits (digits which are either zero or one). Conceptually the bit sequence is infinite on the left, with the most-significant bits being all zeros or all ones. A bitwise operation acts on the individual bits of such a sequence. For example, shifting moves the whole sequence left or right one or more places, reproducing the same pattern moved over. The bitwise operations in Emacs Lisp apply only to integers.

ash
ash (arithmetic shift) shifts the bits in integer to the left count places, or to the right if count is negative. Left shifts introduce zero bits on the right; right shifts discard the rightmost bits. Considered as an integer operation, ash multiplies integer by 2**/count/, and then converts the result to an integer by rounding downward, toward minus infinity. Here are examples of ash, shifting a pattern of bits one place to the left and to the right. These examples show only the low-order bits of the binary pattern; leading bits all agree with the highest-order bit shown. As you can see, shifting left by one is equivalent to multiplying by two, whereas shifting right by one is equivalent to dividing by two and then rounding toward minus infinity.
(ash 7 1) => 14
;; Decimal 7 becomes decimal 14.
...000111
     =>
...001110

(ash 7 -1) => 3
...000111
     =>
...000011

(ash -7 1) => -14
...111001
     =>
...110010

(ash -7 -1) => -4
...111001
     =>
...111100

Here are examples of shifting left or right by two bits:

;  binary values
(ash 5 2)         ;   5  =  ...000101
     => 20         ;      =  ...010100
(ash -5 2)        ;  -5  =  ...111011
     => -20        ;      =  ...101100
(ash 5 -2)
     => 1          ;      =  ...000001
(ash -5 -2)
     => -2         ;      =  ...111110
lsh
lsh, which is an abbreviation for logical shift, shifts the bits in integer to the left count places, or to the right if count is negative, bringing zeros into the vacated bits. If count is negative, then integer must be either a fixnum or a positive bignum, and lsh treats a negative fixnum as if it were unsigned by subtracting twice most-negative-fixnum before shifting, producing a nonnegative result. This quirky behavior dates back to when Emacs supported only fixnums; nowadays ash is a better choice. As lsh behaves like ash except when integer and count are both negative, the following examples focus on these exceptional cases. These examples assume 30-bit fixnums.
; binary values
(ash -7 -1)      ; -7 = ...111111111111111111111111111001
     => -4        ;    = ...111111111111111111111111111100
(lsh -7 -1)
     => 536870908 ;    = ...011111111111111111111111111100
(ash -5 -2)      ; -5 = ...111111111111111111111111111011
     => -2        ;    = ...111111111111111111111111111110
(lsh -5 -2)
     => 268435454 ;    = ...001111111111111111111111111110
logand
This function returns the bitwise AND of the arguments: the /n/th bit is 1 in the result if, and only if, the /n/th bit is 1 in all the arguments. For example, using 4-bit binary numbers, the bitwise AND of 13 and 12 is 12: 1101 combined with 1100 produces 1100. In both the binary numbers, the leftmost two bits are both 1 so the leftmost two bits of the returned value are both 1. However, for the rightmost two bits, each is 0 in at least one of the arguments, so the rightmost two bits of the returned value are both 0. Therefore,
(logand 13 12)
     => 12

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

; binary values

(logand 14 13)     ; 14  =  ...001110
                   ; 13  =  ...001101
     => 12         ; 12  =  ...001100

(logand 14 13 4)   ; 14  =  ...001110
                   ; 13  =  ...001101
                   ;  4  =  ...000100
     => 4          ;  4  =  ...000100

(logand)
     => -1         ; -1  =  ...111111
logior
This function returns the bitwise inclusive OR of its arguments: the /n/th bit is 1 in the result if, and only if, the /n/th bit is 1 in at least one of the arguments. If there are no arguments, the result is 0, which is an identity element for this operation. If logior is passed just one argument, it returns that argument.
; binary values

(logior 12 5)      ; 12  =  ...001100
                   ;  5  =  ...000101
     => 13         ; 13  =  ...001101

(logior 12 5 7)    ; 12  =  ...001100
                   ;  5  =  ...000101
                   ;  7  =  ...000111
     => 15         ; 15  =  ...001111
logxor
This function returns the bitwise exclusive OR of its arguments: the /n/th bit is 1 in the result if, and only if, the /n/th bit is 1 in an odd number of the arguments. If there are no arguments, the result is 0, which is an identity element for this operation. If logxor is passed just one argument, it returns that argument.
; binary values

(logxor 12 5)      ; 12  =  ...001100
                   ;  5  =  ...000101
     => 9          ;  9  =  ...001001

(logxor 12 5 7)    ; 12  =  ...001100
                   ;  5  =  ...000101
                   ;  7  =  ...000111
     => 14         ; 14  =  ...001110
lognot
This function returns the bitwise complement of its argument: the n/th bit is one in the result if, and only if, the /n/th bit is zero in /integer, and vice-versa. The result equals −1 − integer.
(lognot 5)
     => -6
;;  5  =  ...000101
;; becomes
;; -6  =  ...111010
logcount
This function returns the Hamming weight of integer: the number of ones in the binary representation of integer. If integer is negative, it returns the number of zero bits in its two's complement binary representation. The result is always nonnegative.
(logcount 43)     ;  43 = ...000101011
     => 4
(logcount -43)    ; -43 = ...111010101
     => 3

Standard Mathematical Functions

These mathematical functions allow integers as well as floating-point numbers as arguments.

sin
@defunx cos arg @defunx tan arg These are the basic trigonometric functions, with argument arg measured in radians.
asin
The value of (asin ARG) is a number between −pi/2 and pi/2 (inclusive) whose sine is arg. If arg is out of range (outside [−1, 1]), asin returns a NaN.
acos
The value of (acos ARG) is a number between 0 and pi (inclusive) whose cosine is arg. If arg is out of range (outside [−1, 1]), acos returns a NaN.
atan
The value of (atan Y) is a number between −pi/2 and pi/2 (exclusive) whose tangent is y. If the optional second argument x is given, the value of (atan y x) is the angle in radians between the vector [X and the X axis.
exp
This is the exponential function; it returns e to the power arg.
log
This function returns the logarithm of arg, with base base. If you don't specify base, the natural base e is used. If arg or base is negative, log returns a NaN.
expt
This function returns x raised to power y. If both arguments are integers and y is nonnegative, the result is an integer; in this case, overflow signals an error, so watch out. If x is a finite negative number and y is a finite non-integer, expt returns a NaN.
sqrt
This returns the square root of arg. If arg is finite and less than zero, sqrt returns a NaN.

In addition, Emacs defines the following common mathematical constants:

float-e
The mathematical constant e (2.71828…).
float-pi
The mathematical constant pi (3.14159…).

Random Numbers

A deterministic computer program cannot generate true random numbers. For most purposes, pseudo-random numbers suffice. A series of pseudo-random numbers is generated in a deterministic fashion. The numbers are not truly random, but they have certain properties that mimic a random series. For example, all possible values occur equally often in a pseudo-random series. Pseudo-random numbers are generated from a seed value. Starting from any given seed, the random function always generates the same sequence of numbers. By default, Emacs initializes the random seed at startup, in such a way that the sequence of values of random (with overwhelming likelihood) differs in each Emacs run. The random seed is typically initialized from system entropy; however, on obsolescent platforms lacking entropy pools, the seed is taken from less-random volatile data such as the current time. Sometimes you want the random number sequence to be repeatable. For example, when debugging a program whose behavior depends on the random number sequence, it is helpful to get the same behavior in each program run. To make the sequence repeat, execute (random ""). This sets the seed to a constant value for your particular Emacs executable (though it may differ for other Emacs builds). You can use other strings to choose various seed values.

random
This function returns a pseudo-random integer. Repeated calls return a series of pseudo-random integers. If limit is a positive integer, the value is chosen to be nonnegative and less than limit. Otherwise, the value might be any fixnum, i.e., any integer from most-negative-fixnum through most-positive-fixnum (Integer Basics). If limit is a string, it means to choose a new seed based on the string's contents. This causes later calls to random to return a reproducible sequence of results. If limit is t, it means to choose a new seed as if Emacs were restarting. This causes later calls to random to return an unpredictable sequence of results.

If you need a random nonce for cryptographic purposes, using random is typically not the best approach, for several reasons:

  • Although you can use (random t) to consult system entropy, doing so can adversely affect other parts of your program that benefit from reproducible results.
  • The system-dependent pseudo-random number generator (PRNG) used by random is not necessarily suitable for cryptography.
  • A call to (random t) does not give direct access to system entropy; the entropy is passed through the system-dependent PRNG, thus possibly biasing the results.
  • On typical platforms the random seed contains only 32 bits, which is typically narrower than an Emacs fixnum, and is not nearly enough for cryptographic purposes.
  • A (random t) call leaves information about the nonce scattered about Emacs's internal state, increasing the size of the internal attack surface.
  • On obsolescent platforms lacking entropy pools, (random t) is seeded from a cryptographically weak source.
Manual
Emacs Lisp 30.2
Texinfo Node
Numbers
Source Ref
emacs-30.2
Source
View upstream