Function: random

random is a function defined in fns.c.

Signature

(random &optional LIMIT)

Documentation

Return a pseudo-random integer.

By default, return a fixnum; all fixnums are equally likely. With positive integer LIMIT, return random integer in interval [0,LIMIT). With argument t, set the random number seed from the system's entropy pool if available, otherwise from less-random volatile data such as the time. With a string argument, set the seed based on the string's contents.

See Info node (elisp)Random Numbers for more details.

Other relevant functions are documented in the number group.

Probably introduced at or before Emacs version 17.

Shortdoc

;; number
(random 6)
    => 1

Source Code

// Defined in /usr/src/emacs/src/fns.c
{
  EMACS_INT val;

  if (EQ (limit, Qt))
    init_random ();
  else if (STRINGP (limit))
    seed_random (SSDATA (limit), SBYTES (limit));
  if (BIGNUMP (limit))
    {
      if (0 > mpz_sgn (*xbignum_val (limit)))
        xsignal2 (Qwrong_type_argument, Qnatnump, limit);
      return get_random_bignum (limit);
    }

  val = get_random ();
  if (FIXNUMP (limit) && 0 < XFIXNUM (limit))
    while (true)
      {
	/* Return the remainder, except reject the rare case where
	   get_random returns a number so close to INTMASK that the
	   remainder isn't random.  */
	EMACS_INT remainder = val % XFIXNUM (limit);
	if (val - remainder <= INTMASK - XFIXNUM (limit) + 1)
	  return make_fixnum (remainder);
	val = get_random ();
      }
  return make_ufixnum (val);
}