random-state
random-state System Class
Class Precedence List:
random-state, t
Description:
A random state object contains state information used by the pseudo-random number generator. The nature of a random state object is implementation-dependent. It can be printed out and successfully read back in by the same implementation, but might not function correctly as a random state in another implementation.
Implementations are required to provide a read syntax for objects of type random-state, but the specific nature of that syntax is implementation-dependent.
See Also:
*random-state*, random, Section 22.1.3.10 (Printing Random States)
Expanded Reference: random-state
Type Checking
A random-state object encapsulates the state of a pseudo-random number generator. The global variable *random-state* holds the current default random state.
(typep *random-state* 'random-state)
=> T
(random-state-p *random-state*)
=> T
(random-state-p 42)
=> NIL
Creating Random States
Use make-random-state to create new random state objects. It accepts nil (copy current state), t (new randomly initialized state), or an existing random state (copy it).
;; Copy the current random state
(let ((rs (make-random-state nil)))
(typep rs 'random-state))
=> T
;; Create a new randomly initialized state
(let ((rs (make-random-state t)))
(random-state-p rs))
=> T
;; Copy an existing random state
(let* ((rs1 (make-random-state t))
(rs2 (make-random-state rs1)))
;; rs1 and rs2 will produce the same sequence
(= (random 100 rs1) (random 100 rs2)))
=> T
Reproducible Random Sequences
Copying a random state before generating numbers allows you to replay the same sequence.
(let ((saved (make-random-state *random-state*)))
(let ((first-run (list (random 100) (random 100) (random 100))))
(setf *random-state* saved)
(let ((second-run (list (random 100) (random 100) (random 100))))
(equal first-run second-run))))
=> T
Printing and Reading
Random state objects have a printed representation that can be read back, though the format is implementation-dependent.
(let* ((rs (make-random-state t))
(printed (format nil "~S" rs))
(restored (read-from-string printed)))
(random-state-p restored))
=> T