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 (defmethod make-load-form ((random-state random-state
) &optional environment
)
41 (make-load-form-saving-slots random-state
:environment environment
))
43 (defmethod print-object ((state random-state
) stream
)
44 (if (and *print-readably
* (not *read-eval
*))
45 (print-not-readable-error state stream
)
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
(init-random-state)))
83 (/show0
"returning from !RANDOM-COLD-INIT"))
85 ;;; Q: Why is there both MAKE-RANDOM-STATE and SEED-RANDOM-STATE?
86 ;;; A: Because the DEFKNOWN for MAKE-RANDOM-STATE is more restricted
87 ;;; and doesn't accept numerical state.
88 (defun make-random-state (&optional state
)
90 "Make a random state object. The optional STATE argument specifies a seed
91 for deterministic pseudo-random number generation.
93 As per the Common Lisp standard,
94 - If STATE is NIL or not supplied, return a copy of the default
96 - If STATE is a random state, return a copy of it.
97 - If STATE is T, return a randomly initialized state (using operating-system
98 provided randomness where available, otherwise a poor substitute based on
99 internal time and PID).
101 See SB-EXT:SEED-RANDOM-STATE for a SBCL extension to this functionality."
102 (/show0
"entering MAKE-RANDOM-STATE")
103 (seed-random-state state
))
105 (defun fallback-random-seed ()
106 ;; When /dev/urandom is not available, we make do with time and pid
107 ;; Thread ID and/or address of a CONS cell would be even better, but...
108 ;; [ADDRESS-BASED-COUNTER-VAL in 'target-sxhash' could be used here]
109 (/show0
"No /dev/urandom, using randomness from time and pid")
110 (+ (get-internal-real-time)
111 (ash (sb!unix
:unix-getpid
) 32)))
114 (defun os-random-seed ()
116 ;; On unices, we try to read from /dev/urandom and pass the results
117 ;; to our (simple-array (unsigned-byte 32) (*)) processor below.
118 ;; More than 256 bits would provide a false sense of security.
119 ;; If you need more bits than that, you probably also need
120 ;; a better algorithm too.
122 (with-open-file (r "/dev/urandom" :element-type
'(unsigned-byte 32)
123 :direction
:input
:if-does-not-exist
:error
)
124 (let ((a (make-array '(8) :element-type
'(unsigned-byte 32))))
125 (assert (= 8 (read-sequence a r
)))
127 (fallback-random-seed)))
130 (defun os-random-seed ()
131 (/show0
"Getting randomness from CryptGenRandom")
132 (or (sb!win32
:crypt-gen-random
32)
133 (fallback-random-seed)))
135 (defun seed-random-state (&optional state
)
137 "Make a random state object. The optional STATE argument specifies a seed
138 for deterministic pseudo-random number generation.
140 As per the Common Lisp standard for MAKE-RANDOM-STATE,
141 - If STATE is NIL or not supplied, return a copy of the default
143 - If STATE is a random state, return a copy of it.
144 - If STATE is T, return a randomly initialized state (using operating-system
145 provided randomness where available, otherwise a poor substitute based on
146 internal time and pid).
148 As a supported SBCL extension, we also support receiving as a seed an object
149 of the following types:
150 - (SIMPLE-ARRAY (UNSIGNED-BYTE 8) (*))
152 While we support arguments of any size and will mix the provided bits into
153 the random state, it is probably overkill to provide more than 256 bits worth
154 of actual information.
156 This particular SBCL version also accepts an argument of the following type:
157 (SIMPLE-ARRAY (UNSIGNED-BYTE 32) (*))
159 This particular SBCL version uses the popular MT19937 PRNG algorithm, and its
160 internal state only effectively contains about 19937 bits of information.
161 http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
163 (declare (explicit-check))
164 (named-let seed-random-state
((state state
))
166 ;; Easy standard cases
168 (/show0
"copying *RANDOM-STATE*")
169 (%make-random-state
(copy-seq (random-state-state *random-state
*))))
171 (/show0
"copying the provided RANDOM-STATE")
172 (%make-random-state
(copy-seq (random-state-state state
))))
173 ;; Standard case, less easy: try to randomly initialize a state.
175 (/show0
"getting randomness from the operating system")
176 (seed-random-state (os-random-seed)))
177 ;; For convenience to users, we accept (simple-array (unsigned-byte 8) (*))
178 ;; We just convert it to (simple-array (unsigned-byte 32) (*)) in a
179 ;; completely straightforward way.
180 ;; TODO: probably similarly accept other word sizes.
181 ((simple-array (unsigned-byte 8) (*))
182 (/show0
"getting random seed from byte vector (converting to 32-bit-word vector)")
183 (let* ((l (length state
))
185 (r (if (>= l
2496) 0 (mod l
4)))
186 (y (make-array (list m
) :element-type
'(unsigned-byte 32))))
187 (loop for i from
0 below
(- m
(if (zerop r
) 0 1))
191 (ash (aref state
(+ j
1)) 8)
192 (ash (aref state
(+ j
2)) 16)
193 (ash (aref state
(+ j
3)) 24))))
194 (unless (zerop r
) ;; The last word may require special treatment.
195 (let* ((p (1- m
)) (q (* 4 p
)))
198 (if (< 1 r
) (ash (aref state
(+ q
1)) 8) 0)
199 (if (= 3 r
) (ash (aref state
(+ q
2)) 16) 0)))))
200 (seed-random-state y
)))
201 ;; Also for convenience, we accept non-negative integers as seeds.
202 ;; Small ones get passed to init-random-state, as before.
204 (/show0
"getting random seed from 32-bit word")
205 (%make-random-state
(init-random-state state
)))
206 ;; Larger ones ones get trivially chopped into an array of (unsigned-byte 32)
208 (/show0
"getting random seed from bignum (converting to 32-bit-word vector)")
209 (loop with l
= (ceiling (integer-length state
) 32)
210 with s
= (make-array (list l
) :element-type
'(unsigned-byte 32))
213 do
(setf (aref s i
) (ldb (byte 32 p
) state
))
214 finally
(return (seed-random-state s
))))
215 ;; Last but not least, when provided an array of 32-bit words, we truncate
216 ;; it to 19968 bits and mix these into an initial state. We reuse the same
217 ;; method as the authors of the original algorithm. See
218 ;; http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c
219 ;; NB: their mt[i] is our (aref s (+ 3 i))
220 ((simple-array (unsigned-byte 32) (*))
221 (/show0
"getting random seed from 32-bit-word vector")
222 (let ((s (init-random-state 19650218))
223 (i 1) (j 0) (l (length state
)))
224 (loop for k downfrom
(max mt19937-n l
) above
0 do
225 (setf (aref s
(+ i
3))
227 (+ (logxor (aref s
(+ i
3))
229 (logxor (aref s
(+ i
2))
230 (ash (aref s
(+ i
2)) -
30))))
231 (aref state j
) j
))) ;; non-linear
232 (incf i
) (when (>= i mt19937-n
) (setf (aref s
3) (aref s
(+ 2 mt19937-n
)) i
1))
233 (incf j
) (when (>= j l
) (setf j
0)))
234 (loop for k downfrom
(1- mt19937-n
) above
0 do
235 (setf (aref s
(+ i
3))
237 (- (logxor (aref s
(+ i
3))
239 (logxor (aref s
(+ i
2))
240 (ash (aref s
(+ i
2)) -
30))))
242 (incf i
) (when (>= i mt19937-n
) (setf (aref s
3) (aref s
(+ 2 mt19937-n
)) i
1)))
243 (setf (aref s
3) #x80000000
) ;; MSB is 1; assuring non-zero initial array
244 (%make-random-state s
))))))
248 ;;; This function generates a 32bit integer between 0 and #xffffffff
250 #!-sb-fluid
(declaim (inline random-chunk
))
251 ;;; portable implementation
253 (defun random-mt19937-update (state)
254 (declare (type random-state-state state
)
255 (optimize (speed 3) (safety 0)))
257 (declare (type (unsigned-byte 32) y
))
259 ((>= kk
(+ 3 (- mt19937-n mt19937-m
))))
260 (declare (type (mod 628) kk
))
261 (setf y
(logior (logand (aref state kk
) mt19937-upper-mask
)
262 (logand (aref state
(1+ kk
)) mt19937-lower-mask
)))
263 (setf (aref state kk
) (logxor (aref state
(+ kk mt19937-m
))
264 (ash y -
1) (aref state
(logand y
1)))))
265 (do ((kk (+ (- mt19937-n mt19937-m
) 3) (1+ kk
)))
266 ((>= kk
(+ (1- mt19937-n
) 3)))
267 (declare (type (mod 628) kk
))
268 (setf y
(logior (logand (aref state kk
) mt19937-upper-mask
)
269 (logand (aref state
(1+ kk
)) mt19937-lower-mask
)))
270 (setf (aref state kk
) (logxor (aref state
(+ kk
(- mt19937-m mt19937-n
)))
271 (ash y -
1) (aref state
(logand y
1)))))
272 (setf y
(logior (logand (aref state
(+ 3 (1- mt19937-n
)))
274 (logand (aref state
3) mt19937-lower-mask
)))
275 (setf (aref state
(+ 3 (1- mt19937-n
)))
276 (logxor (aref state
(+ 3 (1- mt19937-m
)))
277 (ash y -
1) (aref state
(logand y
1)))))
280 (defun random-chunk (state)
281 (declare (type random-state state
))
282 (let* ((state (random-state-state state
))
284 (declare (type (mod 628) k
))
285 (when (= k mt19937-n
)
286 (random-mt19937-update state
)
288 (setf (aref state
2) (1+ k
))
289 (let ((y (aref state
(+ 3 k
))))
290 (declare (type (unsigned-byte 32) y
))
291 (setf y
(logxor y
(ash y -
11)))
292 (setf y
(logxor y
(ash (logand y
(ash mt19937-b -
7)) 7)))
293 (setf y
(logxor y
(ash (logand y
(ash mt19937-c -
15)) 15)))
294 (setf y
(logxor y
(ash y -
18)))
297 ;;; Using inline VOP support, only available on the x86 so far.
299 ;;; FIXME: It would be nice to have some benchmark numbers on this.
300 ;;; My inclination is to get rid of the nonportable implementation
301 ;;; unless the performance difference is just enormous.
303 (defun random-chunk (state)
304 (declare (type random-state state
))
305 (sb!vm
::random-mt19937
(random-state-state state
)))
307 #!-sb-fluid
(declaim (inline big-random-chunk
))
308 (defun big-random-chunk (state)
309 (declare (type random-state state
))
310 (logior (ash (random-chunk state
) 32)
311 (random-chunk state
)))
313 ;;; Handle the single or double float case of RANDOM. We generate a
314 ;;; float between 0.0 and 1.0 by clobbering the significand of 1.0
315 ;;; with random bits, then subtracting 1.0. This hides the fact that
316 ;;; we have a hidden bit.
317 #!-sb-fluid
(declaim (inline %random-single-float %random-double-float
))
318 (declaim (ftype (function ((single-float (0f0)) random-state
)
320 %random-single-float
))
321 (defun %random-single-float
(arg state
)
322 (declare (type (single-float (0f0)) arg
)
323 (type random-state state
))
325 (- (make-single-float
326 (dpb (ash (random-chunk state
)
327 (- sb
!vm
:single-float-digits n-random-chunk-bits
))
328 sb
!vm
:single-float-significand-byte
329 (single-float-bits 1.0)))
331 (declaim (ftype (function ((double-float (0d0)) random-state
)
333 %random-double-float
))
337 (defun %random-double-float
(arg state
)
338 (declare (type (double-float (0d0)) arg
)
339 (type random-state state
))
340 (* (float (random-chunk state
) 1d0
) (/ 1d0
(expt 2 32))))
344 (defun %random-double-float
(arg state
)
345 (declare (type (double-float (0d0)) arg
)
346 (type random-state state
))
348 (- (sb!impl
::make-double-float
349 (dpb (ash (random-chunk state
)
350 (- sb
!vm
:double-float-digits n-random-chunk-bits
32))
351 sb
!vm
:double-float-significand-byte
352 (sb!impl
::double-float-high-bits
1d0
))
353 (random-chunk state
))
356 ;;; using a faster inline VOP
358 (defun %random-double-float
(arg state
)
359 (declare (type (double-float (0d0)) arg
)
360 (type random-state state
))
361 (let ((state-vector (random-state-state state
)))
363 (- (sb!impl
::make-double-float
364 (dpb (ash (sb!vm
::random-mt19937 state-vector
)
365 (- sb
!vm
:double-float-digits n-random-chunk-bits
367 sb
!vm
:double-float-significand-byte
368 (sb!impl
::double-float-high-bits
1d0
))
369 (sb!vm
::random-mt19937 state-vector
))
375 ;;; Generate and return a pseudo random fixnum less than ARG. To achieve
376 ;;; equidistribution an accept-reject loop is used.
377 ;;; No extra effort is made to detect the case of ARG being a power of
378 ;;; two where rejection is not possible, as the cost of checking for
379 ;;; this case is the same as doing the rejection test. When ARG is
380 ;;; larger than (expt 2 N-RANDOM-CHUNK-BITS), which can only happen if
381 ;;; the random chunk size is half the word size, two random chunks are
382 ;;; used in each loop iteration, otherwise only one. Finally, the
383 ;;; rejection probability could often be reduced by not masking the
384 ;;; chunk but rejecting only values as least as large as the largest
385 ;;; multiple of ARG that fits in a chunk (or two), but this is not done
386 ;;; as the speed gains due to needing fewer loop iterations are by far
387 ;;; outweighted by the cost of the two divisions required (one to find
388 ;;; the multiplier and one to bring the result into the correct range).
389 #!-sb-fluid
(declaim (inline %random-fixnum
))
390 (defun %random-fixnum
(arg state
)
391 (declare (type (integer 1 #.sb
!xc
:most-positive-fixnum
) arg
)
392 (type random-state state
))
395 (let* ((n-bits (integer-length (1- arg
)))
396 (mask (1- (ash 1 n-bits
))))
397 (macrolet ((accept-reject-loop (generator)
399 (let ((bits (logand mask
(,generator state
))))
402 (assert (<= n-bits
(* 2 n-random-chunk-bits
)))
403 (if (<= n-bits n-random-chunk-bits
)
404 (accept-reject-loop random-chunk
)
405 (accept-reject-loop big-random-chunk
))))))
407 (defun random (arg &optional
(state *random-state
*))
408 #!-sb-fluid
(declare (inline %random-fixnum
409 %random-single-float %random-double-float
410 #!+long-float %random-long-float
))
411 (declare (explicit-check))
413 ((and (fixnump arg
) (> arg
0))
414 (%random-fixnum arg state
))
415 ((and (typep arg
'single-float
) (> arg
0.0f0
))
416 (%random-single-float arg state
))
417 ((and (typep arg
'double-float
) (> arg
0.0d0
))
418 (%random-double-float arg state
))
420 ((and (typep arg
'long-float
) (> arg
0.0l0))
421 (%random-long-float arg state
))
422 ((and (bignump arg
) (> arg
0))
423 (%random-bignum arg state
))
425 (error 'simple-type-error
426 :expected-type
'(or (integer 1) (float (0))) :datum arg
427 :format-control
"~@<Argument is neither a positive integer nor a ~
428 positive float: ~2I~_~S~:>"
429 :format-arguments
(list arg
)))))