1 ;;;; This implementation of RANDOM is based on the Mersenne Twister random
2 ;;;; number generator "MT19937" due to Matsumoto and Nishimura. See:
3 ;;;; Makoto Matsumoto and T. Nishimura, "Mersenne twister: A
4 ;;;; 623-dimensionally equidistributed uniform pseudorandom number
5 ;;;; generator.", ACM Transactions on Modeling and Computer Simulation,
6 ;;;; Vol. 8, No. 1, January pp.3-30 (1998) DOI:10.1145/272991.272995
7 ;;;; http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
9 ;;;; This software is part of the SBCL system. See the README file for
10 ;;;; more information.
12 ;;;; This software is derived from the CMU CL system, which was
13 ;;;; written at Carnegie Mellon University and released into the
14 ;;;; public domain. The software is in the public domain and is
15 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
16 ;;;; files for more information.
18 (in-package "SB!KERNEL")
21 (defconstant mt19937-n 624)
22 (defconstant mt19937-m 397)
23 (defconstant mt19937-upper-mask #x80000000)
24 (defconstant mt19937-lower-mask #x7FFFFFFF)
25 (defconstant mt19937-a #x9908B0DF)
26 (defconstant mt19937-b #x9D2C5680)
27 (defconstant mt19937-c #xEFC60000)
31 ;;; The state is stored in a (simple-array (unsigned-byte 32) (627))
32 ;;; wrapped in a random-state structure:
34 ;;; 0-1: Constant matrix A. [0, #x9908b0df]
38 (deftype random-state-state () `(simple-array (unsigned-byte 32) (,(+ 3 mt19937-n))))
40 (def!method make-load-form ((random-state random-state) &optional environment)
41 (make-load-form-saving-slots random-state :environment environment))
43 (def!method print-object ((state random-state) stream)
44 (if (and *print-readably* (not *read-eval*))
45 (error 'print-not-readable :object state)
46 (format stream "#S(~S ~S #.~S)"
49 `(make-array ,(+ 3 mt19937-n)
53 ',(coerce (random-state-state state) 'list)))))
55 ;;; Generate and initialize a new random-state array. Index is
56 ;;; initialized to 1 and the states to 32bit integers excluding zero.
58 ;;; Seed - A 32bit number.
60 ;;; See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier.
61 ;;; In the previous versions, MSBs of the seed affect only MSBs of the array.
62 (defun init-random-state (&optional (seed 5489) state)
63 (declare (type (unsigned-byte 32) seed))
64 (let ((state (or state (make-array 627 :element-type '(unsigned-byte 32)))))
65 (check-type state random-state-state)
66 (setf (aref state 0) 0)
67 (setf (aref state 1) mt19937-a)
68 (setf (aref state 2) mt19937-n)
69 (loop for i below mt19937-n
74 (logxor s (ash s -30)))
76 do (setf (aref state p) s))
79 (defvar *random-state*)
80 (defun !random-cold-init ()
81 (/show0 "entering !RANDOM-COLD-INIT")
82 (setf *random-state* (%make-random-state))
83 (/show0 "returning from !RANDOM-COLD-INIT"))
85 (defun make-random-state (&optional state)
87 "Make a random state object. The optional STATE argument specifies a seed
88 for deterministic pseudo-random number generation.
90 As per the Common Lisp standard,
91 - If STATE is NIL or not supplied or is NIL, return a copy of the default
93 - If STATE is a random state, return a copy of it.
94 - If STATE is T, return a randomly initialized state (using operating-system
95 provided randomness source where available, otherwise a poor substitute
96 based on internal time and pid)
98 See SB-EXT:SEED-RANDOM-STATE for a SBCL extension to this functionality."
99 (/show0 "entering MAKE-RANDOM-STATE")
100 (check-type state (or boolean random-state))
101 (seed-random-state state))
103 (defun seed-random-state (&optional state)
105 "Make a random state object. The optional STATE argument specifies a seed
106 for deterministic pseudo-random number generation.
108 As per the Common Lisp standard for MAKE-RANDOM-STATE,
109 - If STATE is NIL or not supplied or is NIL, return a copy of the default
111 - If STATE is a random state, return a copy of it.
112 - If STATE is T, return a randomly initialized state (using operating-system
113 provided randomness source where available, otherwise a poor substitute
114 based on internal time and pid)
116 As a supported SBCL extension, we also support receiving as a seed an object
117 of the following types:
118 - (SIMPLE-ARRAY (UNSIGNED-BYTE 8) (*))
120 While we support arguments of any size and will mix the provided bits into
121 the random state, it is probably overkill to provide more than 256 bits worth
122 of actual information.
124 This particular SBCL version also accepts an argument of the following type:
125 - (SIMPLE-ARRAY (UNSIGNED-BYTE 32) (*))
127 This particular SBCL version uses the popular MT19937 PRNG algorithm, and its
128 internal state only effectively contains about 19937 bits of information.
129 http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
132 ;; Easy standard cases
134 (/show0 "copying *RANDOM-STATE*")
135 (%make-random-state :state (copy-seq (random-state-state *random-state*))))
137 (/show0 "copying the provided RANDOM-STATE")
138 (%make-random-state :state (copy-seq (random-state-state state))))
139 ;; Standard case, less easy: try to randomly initialize a state.
141 (/show0 "getting randomness from the operating system")
144 ;; On unices, we try to read from /dev/urandom and pass the results
145 ;; to our (simple-array (unsigned-byte 32) (*)) processor below.
146 ;; More than 256 bits would provide a false sense of security.
147 ;; If you need more bits than that, you probably also need
148 ;; a better algorithm too.
151 (with-open-file (r "/dev/urandom" :element-type '(unsigned-byte 32)
152 :direction :input :if-does-not-exist :error)
153 (let ((a (make-array '(8) :element-type '(unsigned-byte 32))))
154 (assert (= 8 (read-sequence a r)))
156 ;; When /dev/urandom is not available, we make do with time and pid
157 ;; Thread ID and/or address of a CONS cell would be even better, but...
159 (/show0 "No /dev/urandom, using randomness from time and pid")
160 (+ (get-internal-real-time)
161 #!+unix (ash (sb!unix:unix-getpid) 32))))))
162 ;; For convenience to users, we accept (simple-array (unsigned-byte 8) (*))
163 ;; We just convert it to (simple-array (unsigned-byte 32) (*)) in a
164 ;; completely straightforward way.
165 ;; TODO: probably similarly accept other word sizes.
166 ((simple-array (unsigned-byte 8) (*))
167 (/show0 "getting random seed from byte vector (converting to 32-bit-word vector)")
168 (let* ((l (length state))
170 (r (if (>= l 2496) 0 (mod l 4)))
171 (y (make-array (list m) :element-type '(unsigned-byte 32))))
172 (loop for i from 0 below (- m (if (zerop r) 0 1))
176 (ash (aref state (+ j 1)) 8)
177 (ash (aref state (+ j 2)) 16)
178 (ash (aref state (+ j 3)) 24))))
179 (unless (zerop r) ;; The last word may require special treatment.
180 (let* ((p (1- m)) (q (* 4 p)))
183 (if (< 1 r) (ash (aref state (+ q 1)) 8) 0)
184 (if (= 3 r) (ash (aref state (+ q 2)) 16) 0)))))
185 (seed-random-state y)))
186 ;; Also for convenience, we accept non-negative integers as seeds.
187 ;; Small ones get passed to init-random-state, as before.
189 (/show0 "getting random seed from 32-bit word")
190 (%make-random-state :state (init-random-state state)))
191 ;; Larger ones ones get trivially chopped into an array of (unsigned-byte 32)
193 (/show0 "getting random seed from bignum (converting to 32-bit-word vector)")
194 (loop with l = (ceiling (integer-length state) 32)
195 with s = (make-array (list l) :element-type '(unsigned-byte 32))
198 do (setf (aref s i) (ldb (byte 32 p) state))
199 finally (return (seed-random-state s))))
200 ;; Last but not least, when provided an array of 32-bit words, we truncate
201 ;; it to 19968 bits and mix these into an initial state. We reuse the same
202 ;; method as the authors of the original algorithm. See
203 ;; http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c
204 ;; NB: their mt[i] is our (aref s (+ 3 i))
205 ((simple-array (unsigned-byte 32) (*))
206 (/show0 "getting random seed from 32-bit-word vector")
207 (let ((s (init-random-state 19650218))
208 (i 1) (j 0) (l (length state)))
209 (loop for k downfrom (max mt19937-n l) above 0 do
210 (setf (aref s (+ i 3))
212 (+ (logxor (aref s (+ i 3))
214 (logxor (aref s (+ i 2))
215 (ash (aref s (+ i 2)) -30))))
216 (aref state j) j))) ;; non-linear
217 (incf i) (when (>= i mt19937-n) (setf (aref s 3) (aref s (+ 2 mt19937-n)) i 1))
218 (incf j) (when (>= j l) (setf j 0)))
219 (loop for k downfrom (1- mt19937-n) above 0 do
220 (setf (aref s (+ i 3))
222 (- (logxor (aref s (+ i 3))
224 (logxor (aref s (+ i 2))
225 (ash (aref s (+ i 2)) -30))))
227 (incf i) (when (>= i mt19937-n) (setf (aref s 3) (aref s (+ 2 mt19937-n)) i 1)))
228 (setf (aref s 3) #x80000000) ;; MSB is 1; assuring non-zero initial array
229 (%make-random-state :state s)))))
233 ;;; This function generates a 32bit integer between 0 and #xffffffff
235 #!-sb-fluid (declaim (inline random-chunk))
236 ;;; portable implementation
238 (defun random-mt19937-update (state)
239 (declare (type random-state-state state)
240 (optimize (speed 3) (safety 0)))
242 (declare (type (unsigned-byte 32) y))
244 ((>= kk (+ 3 (- mt19937-n mt19937-m))))
245 (declare (type (mod 628) kk))
246 (setf y (logior (logand (aref state kk) mt19937-upper-mask)
247 (logand (aref state (1+ kk)) mt19937-lower-mask)))
248 (setf (aref state kk) (logxor (aref state (+ kk mt19937-m))
249 (ash y -1) (aref state (logand y 1)))))
250 (do ((kk (+ (- mt19937-n mt19937-m) 3) (1+ kk)))
251 ((>= kk (+ (1- mt19937-n) 3)))
252 (declare (type (mod 628) kk))
253 (setf y (logior (logand (aref state kk) mt19937-upper-mask)
254 (logand (aref state (1+ kk)) mt19937-lower-mask)))
255 (setf (aref state kk) (logxor (aref state (+ kk (- mt19937-m mt19937-n)))
256 (ash y -1) (aref state (logand y 1)))))
257 (setf y (logior (logand (aref state (+ 3 (1- mt19937-n)))
259 (logand (aref state 3) mt19937-lower-mask)))
260 (setf (aref state (+ 3 (1- mt19937-n)))
261 (logxor (aref state (+ 3 (1- mt19937-m)))
262 (ash y -1) (aref state (logand y 1)))))
265 (defun random-chunk (state)
266 (declare (type random-state state))
267 (let* ((state (random-state-state state))
269 (declare (type (mod 628) k))
270 (when (= k mt19937-n)
271 (random-mt19937-update state)
273 (setf (aref state 2) (1+ k))
274 (let ((y (aref state (+ 3 k))))
275 (declare (type (unsigned-byte 32) y))
276 (setf y (logxor y (ash y -11)))
277 (setf y (logxor y (ash (logand y (ash mt19937-b -7)) 7)))
278 (setf y (logxor y (ash (logand y (ash mt19937-c -15)) 15)))
279 (setf y (logxor y (ash y -18)))
282 ;;; Using inline VOP support, only available on the x86 so far.
284 ;;; FIXME: It would be nice to have some benchmark numbers on this.
285 ;;; My inclination is to get rid of the nonportable implementation
286 ;;; unless the performance difference is just enormous.
288 (defun random-chunk (state)
289 (declare (type random-state state))
290 (sb!vm::random-mt19937 (random-state-state state)))
292 #!-sb-fluid (declaim (inline big-random-chunk))
293 (defun big-random-chunk (state)
294 (declare (type random-state state))
295 (logand (1- (expt 2 64))
296 (logior (ash (random-chunk state) 32)
297 (random-chunk state))))
299 ;;; Handle the single or double float case of RANDOM. We generate a
300 ;;; float between 0.0 and 1.0 by clobbering the significand of 1.0
301 ;;; with random bits, then subtracting 1.0. This hides the fact that
302 ;;; we have a hidden bit.
303 #!-sb-fluid (declaim (inline %random-single-float %random-double-float))
304 (declaim (ftype (function ((single-float (0f0)) random-state)
306 %random-single-float))
307 (defun %random-single-float (arg state)
308 (declare (type (single-float (0f0)) arg)
309 (type random-state state))
311 (- (make-single-float
312 (dpb (ash (random-chunk state)
313 (- sb!vm:single-float-digits random-chunk-length))
314 sb!vm:single-float-significand-byte
315 (single-float-bits 1.0)))
317 (declaim (ftype (function ((double-float (0d0)) random-state)
319 %random-double-float))
323 (defun %random-double-float (arg state)
324 (declare (type (double-float (0d0)) arg)
325 (type random-state state))
326 (* (float (random-chunk state) 1d0) (/ 1d0 (expt 2 32))))
330 (defun %random-double-float (arg state)
331 (declare (type (double-float (0d0)) arg)
332 (type random-state state))
334 (- (sb!impl::make-double-float
335 (dpb (ash (random-chunk state)
336 (- sb!vm:double-float-digits random-chunk-length 32))
337 sb!vm:double-float-significand-byte
338 (sb!impl::double-float-high-bits 1d0))
339 (random-chunk state))
342 ;;; using a faster inline VOP
344 (defun %random-double-float (arg state)
345 (declare (type (double-float (0d0)) arg)
346 (type random-state state))
347 (let ((state-vector (random-state-state state)))
349 (- (sb!impl::make-double-float
350 (dpb (ash (sb!vm::random-mt19937 state-vector)
351 (- sb!vm:double-float-digits random-chunk-length
353 sb!vm:double-float-significand-byte
354 (sb!impl::double-float-high-bits 1d0))
355 (sb!vm::random-mt19937 state-vector))
361 (defun %random-integer (arg state)
362 (declare (type (integer 1) arg) (type random-state state))
363 (let ((shift (- random-chunk-length random-integer-overlap)))
364 (do ((bits (random-chunk state)
365 (logxor (ash bits shift) (random-chunk state)))
366 (count (+ (integer-length arg)
367 (- random-integer-extra-bits shift))
371 (declare (fixnum count)))))
373 (defun random (arg &optional (state *random-state*))
374 (declare (inline %random-single-float %random-double-float
375 #!+long-float %random-long-float))
377 ((and (fixnump arg) (<= arg random-fixnum-max) (> arg 0))
378 (rem (random-chunk state) arg))
379 ((and (typep arg 'single-float) (> arg 0.0f0))
380 (%random-single-float arg state))
381 ((and (typep arg 'double-float) (> arg 0.0d0))
382 (%random-double-float arg state))
384 ((and (typep arg 'long-float) (> arg 0.0l0))
385 (%random-long-float arg state))
386 ((and (integerp arg) (> arg 0))
387 (%random-integer arg state))
389 (error 'simple-type-error
390 :expected-type '(or (integer 1) (float (0))) :datum arg
391 :format-control "~@<Argument is neither a positive integer nor a ~
392 positive float: ~2I~_~S~:>"
393 :format-arguments (list arg)))))