*random-state*
∗random-state∗ Variable
Value Type:
a random state.
Initial Value:
implementation-dependent.
Description:
The current random state, which is used, for example, by the function random when a random state is not explicitly supplied.
Examples:
(random-state-p \*random-state\*) → true
(setq snap-shot (make-random-state))
;; The series from any given point is random,
;; but if you backtrack to that point, you get the same series.
(list (loop for i from 1 to 10 collect (random))
(let ((\*random-state\* snap-shot))
(loop for i from 1 to 10 collect (random)))
(loop for i from 1 to 10 collect (random))
(let ((\*random-state\* snap-shot))
(loop for i from 1 to 10 collect (random))))
→ ((19 16 44 19 96 15 76 96 13 61)
(19 16 44 19 96 15 76 96 13 61)
(16 67 0 43 70 79 58 5 63 50)
(16 67 0 43 70 79 58 5 63 50))
Affected By:
The implementation.
random.
See Also:
make-random-state, random, random-state
Notes:
Binding *random-state* to a different random state object correctly saves and restores the old random state object.
Expanded Reference: *random-state*
Examining the Current State
The *random-state* variable holds the current default random state used by random when no explicit state argument is provided.
*random-state*
;; => #S(RANDOM-STATE ...) (implementation-dependent printed form)
(random-state-p *random-state*)
=> T
How random Uses the State
Calling random without a state argument uses and mutates *random-state*. Each call advances the state.
;; These calls use *random-state* implicitly
(random 100)
;; => impl-dependent
(random 100)
;; => impl-dependent
;; Equivalent to explicitly passing *random-state*
(random 100 *random-state*)
;; => impl-dependent
Binding for Reproducibility
Binding *random-state* with let creates a local copy, allowing reproducible sequences without affecting the global state.
(let ((*random-state* (make-random-state nil)))
;; This binding is local; the global *random-state* is unaffected
(list (random 100) (random 100) (random 100)))
;; => impl-dependent
Resetting for Testing
For deterministic testing, save and restore the random state so that tests produce the same results each time.
(defvar *test-random-state* (make-random-state t))
(defun deterministic-random-values (n max)
"Generate N random values below MAX using a fixed seed."
(let ((*random-state* (make-random-state *test-random-state*)))
(loop repeat n collect (random max))))
;; Same result each call (since we copy the same saved state each time)
(equal (deterministic-random-values 5 100)
(deterministic-random-values 5 100))
=> T