Remove single use function, revise comment, fix inlining failure
[sbcl.git] / src / code / target-random.lisp
blob652fdd996dc943abc05aad83ff8054410b65035f
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.
11 ;;;;
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")
20 ;;;; Constants
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)
29 ;;;; RANDOM-STATEs
31 ;;; The state is stored in a (simple-array (unsigned-byte 32) (627))
32 ;;; wrapped in a random-state structure:
33 ;;;
34 ;;; 0-1: Constant matrix A. [0, #x9908b0df]
35 ;;; 2: Index k.
36 ;;; 3-626: State.
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)"
47 'random-state
48 ':state
49 `(make-array ,(+ 3 mt19937-n)
50 :element-type
51 '(unsigned-byte 32)
52 :initial-contents
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.
57 ;;;
58 ;;; Seed - A 32bit number.
59 ;;;
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
70 for p from 3
71 for s = seed then
72 (logand #xFFFFFFFF
73 (+ (* 1812433253
74 (logxor s (ash s -30)))
75 i))
76 do (setf (aref state p) s))
77 state))
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)
89 "Make a random state object. The optional STATE argument specifies a seed
90 for deterministic pseudo-random number generation.
92 As per the Common Lisp standard,
93 - If STATE is NIL or not supplied, return a copy of the default
94 *RANDOM-STATE*.
95 - If STATE is a random state, return a copy of it.
96 - If STATE is T, return a randomly initialized state (using operating-system
97 provided randomness where available, otherwise a poor substitute based on
98 internal time and PID).
100 See SB-EXT:SEED-RANDOM-STATE for a SBCL extension to this functionality."
101 (/show0 "entering MAKE-RANDOM-STATE")
102 (seed-random-state state))
104 (defun fallback-random-seed ()
105 ;; When /dev/urandom is not available, we make do with time and pid
106 ;; Thread ID and/or address of a CONS cell would be even better, but...
107 ;; [ADDRESS-BASED-COUNTER-VAL in 'target-sxhash' could be used here]
108 (/show0 "No /dev/urandom, using randomness from time and pid")
109 (+ (get-internal-real-time)
110 (ash (sb!unix:unix-getpid) 32)))
112 #!-win32
113 (defun os-random-seed ()
115 ;; On unices, we try to read from /dev/urandom and pass the results
116 ;; to our (simple-array (unsigned-byte 32) (*)) processor below.
117 ;; More than 256 bits would provide a false sense of security.
118 ;; If you need more bits than that, you probably also need
119 ;; a better algorithm too.
120 (ignore-errors
121 (with-open-file (r "/dev/urandom" :element-type '(unsigned-byte 32)
122 :direction :input :if-does-not-exist :error)
123 (let ((a (make-array '(8) :element-type '(unsigned-byte 32))))
124 (assert (= 8 (read-sequence a r)))
125 a)))
126 (fallback-random-seed)))
128 #!+win32
129 (defun os-random-seed ()
130 (/show0 "Getting randomness from CryptGenRandom")
131 (or (sb!win32:crypt-gen-random 32)
132 (fallback-random-seed)))
134 (defun seed-random-state (&optional state)
135 "Make a random state object. The optional STATE argument specifies a seed
136 for deterministic pseudo-random number generation.
138 As per the Common Lisp standard for MAKE-RANDOM-STATE,
139 - If STATE is NIL or not supplied, return a copy of the default
140 *RANDOM-STATE*.
141 - If STATE is a random state, return a copy of it.
142 - If STATE is T, return a randomly initialized state (using operating-system
143 provided randomness where available, otherwise a poor substitute based on
144 internal time and pid).
146 As a supported SBCL extension, we also support receiving as a seed an object
147 of the following types:
148 - (SIMPLE-ARRAY (UNSIGNED-BYTE 8) (*))
149 - UNSIGNED-BYTE
150 While we support arguments of any size and will mix the provided bits into
151 the random state, it is probably overkill to provide more than 256 bits worth
152 of actual information.
154 This particular SBCL version also accepts an argument of the following type:
155 (SIMPLE-ARRAY (UNSIGNED-BYTE 32) (*))
157 This particular SBCL version uses the popular MT19937 PRNG algorithm, and its
158 internal state only effectively contains about 19937 bits of information.
159 http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
161 (declare (explicit-check))
162 (named-let seed-random-state ((state state))
163 (etypecase state
164 ;; Easy standard cases
165 (null
166 (/show0 "copying *RANDOM-STATE*")
167 (%make-random-state (copy-seq (random-state-state *random-state*))))
168 (random-state
169 (/show0 "copying the provided RANDOM-STATE")
170 (%make-random-state (copy-seq (random-state-state state))))
171 ;; Standard case, less easy: try to randomly initialize a state.
172 ((eql t)
173 (/show0 "getting randomness from the operating system")
174 (seed-random-state (os-random-seed)))
175 ;; For convenience to users, we accept (simple-array (unsigned-byte 8) (*))
176 ;; We just convert it to (simple-array (unsigned-byte 32) (*)) in a
177 ;; completely straightforward way.
178 ;; TODO: probably similarly accept other word sizes.
179 ((simple-array (unsigned-byte 8) (*))
180 (/show0 "getting random seed from byte vector (converting to 32-bit-word vector)")
181 (let* ((l (length state))
182 (m (ceiling l 4))
183 (r (if (>= l 2496) 0 (mod l 4)))
184 (y (make-array (list m) :element-type '(unsigned-byte 32))))
185 (loop for i from 0 below (- m (if (zerop r) 0 1))
186 for j = (* i 4) do
187 (setf (aref y i)
188 (+ (aref state j)
189 (ash (aref state (+ j 1)) 8)
190 (ash (aref state (+ j 2)) 16)
191 (ash (aref state (+ j 3)) 24))))
192 (unless (zerop r) ;; The last word may require special treatment.
193 (let* ((p (1- m)) (q (* 4 p)))
194 (setf (aref y p)
195 (+ (aref state q)
196 (if (< 1 r) (ash (aref state (+ q 1)) 8) 0)
197 (if (= 3 r) (ash (aref state (+ q 2)) 16) 0)))))
198 (seed-random-state y)))
199 ;; Also for convenience, we accept non-negative integers as seeds.
200 ;; Small ones get passed to init-random-state, as before.
201 ((unsigned-byte 32)
202 (/show0 "getting random seed from 32-bit word")
203 (%make-random-state (init-random-state state)))
204 ;; Larger ones ones get trivially chopped into an array of (unsigned-byte 32)
205 ((unsigned-byte)
206 (/show0 "getting random seed from bignum (converting to 32-bit-word vector)")
207 (loop with l = (ceiling (integer-length state) 32)
208 with s = (make-array (list l) :element-type '(unsigned-byte 32))
209 for i below l
210 for p from 0 by 32
211 do (setf (aref s i) (ldb (byte 32 p) state))
212 finally (return (seed-random-state s))))
213 ;; Last but not least, when provided an array of 32-bit words, we truncate
214 ;; it to 19968 bits and mix these into an initial state. We reuse the same
215 ;; method as the authors of the original algorithm. See
216 ;; http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c
217 ;; NB: their mt[i] is our (aref s (+ 3 i))
218 ((simple-array (unsigned-byte 32) (*))
219 (/show0 "getting random seed from 32-bit-word vector")
220 (let ((s (init-random-state 19650218))
221 (i 1) (j 0) (l (length state)))
222 (loop for k downfrom (max mt19937-n l) above 0 do
223 (setf (aref s (+ i 3))
224 (logand #xFFFFFFFF
225 (+ (logxor (aref s (+ i 3))
226 (* 1664525
227 (logxor (aref s (+ i 2))
228 (ash (aref s (+ i 2)) -30))))
229 (aref state j) j))) ;; non-linear
230 (incf i) (when (>= i mt19937-n) (setf (aref s 3) (aref s (+ 2 mt19937-n)) i 1))
231 (incf j) (when (>= j l) (setf j 0)))
232 (loop for k downfrom (1- mt19937-n) above 0 do
233 (setf (aref s (+ i 3))
234 (logand #xFFFFFFFF
235 (- (logxor (aref s (+ i 3))
236 (* 1566083941
237 (logxor (aref s (+ i 2))
238 (ash (aref s (+ i 2)) -30))))
239 i))) ;; non-linear
240 (incf i) (when (>= i mt19937-n) (setf (aref s 3) (aref s (+ 2 mt19937-n)) i 1)))
241 (setf (aref s 3) #x80000000) ;; MSB is 1; assuring non-zero initial array
242 (%make-random-state s))))))
244 ;;;; random entries
246 ;;; This function generates a 32bit integer between 0 and #xffffffff
247 ;;; inclusive.
248 #!-sb-fluid (declaim (inline random-chunk))
249 ;;; portable implementation
250 #!-x86
251 (defun random-mt19937-update (state)
252 (declare (type random-state-state state)
253 (optimize (speed 3) (safety 0)))
254 (let ((y 0))
255 (declare (type (unsigned-byte 32) y))
256 (do ((kk 3 (1+ kk)))
257 ((>= kk (+ 3 (- mt19937-n mt19937-m))))
258 (declare (type (mod 628) kk))
259 (setf y (logior (logand (aref state kk) mt19937-upper-mask)
260 (logand (aref state (1+ kk)) mt19937-lower-mask)))
261 (setf (aref state kk) (logxor (aref state (+ kk mt19937-m))
262 (ash y -1) (aref state (logand y 1)))))
263 (do ((kk (+ (- mt19937-n mt19937-m) 3) (1+ kk)))
264 ((>= kk (+ (1- mt19937-n) 3)))
265 (declare (type (mod 628) kk))
266 (setf y (logior (logand (aref state kk) mt19937-upper-mask)
267 (logand (aref state (1+ kk)) mt19937-lower-mask)))
268 (setf (aref state kk) (logxor (aref state (+ kk (- mt19937-m mt19937-n)))
269 (ash y -1) (aref state (logand y 1)))))
270 (setf y (logior (logand (aref state (+ 3 (1- mt19937-n)))
271 mt19937-upper-mask)
272 (logand (aref state 3) mt19937-lower-mask)))
273 (setf (aref state (+ 3 (1- mt19937-n)))
274 (logxor (aref state (+ 3 (1- mt19937-m)))
275 (ash y -1) (aref state (logand y 1)))))
276 (values))
277 #!-x86
278 (defun random-chunk (state)
279 (declare (type random-state state))
280 (let* ((state (random-state-state state))
281 (k (aref state 2)))
282 (declare (type (mod 628) k))
283 (when (= k mt19937-n)
284 (random-mt19937-update state)
285 (setf k 0))
286 (setf (aref state 2) (1+ k))
287 (let ((y (aref state (+ 3 k))))
288 (declare (type (unsigned-byte 32) y))
289 (setf y (logxor y (ash y -11)))
290 (setf y (logxor y (ash (logand y (ash mt19937-b -7)) 7)))
291 (setf y (logxor y (ash (logand y (ash mt19937-c -15)) 15)))
292 (setf y (logxor y (ash y -18)))
293 y)))
295 ;;; Using inline VOP support, only available on the x86 so far.
297 ;;; FIXME: It would be nice to have some benchmark numbers on this.
298 ;;; My inclination is to get rid of the nonportable implementation
299 ;;; unless the performance difference is just enormous.
300 #!+x86
301 (defun random-chunk (state)
302 (declare (type random-state state))
303 (sb!vm::random-mt19937 (random-state-state state)))
305 #!-sb-fluid (declaim (inline big-random-chunk))
306 (defun big-random-chunk (state)
307 (declare (type random-state state))
308 (logior (ash (random-chunk state) 32)
309 (random-chunk state)))
311 ;;; Handle the single or double float case of RANDOM. We generate a
312 ;;; float between 0.0 and 1.0 by clobbering the significand of 1.0
313 ;;; with random bits, then subtracting 1.0. This hides the fact that
314 ;;; we have a hidden bit.
315 #!-sb-fluid (declaim (inline %random-single-float %random-double-float))
316 (declaim (ftype (function ((single-float (0f0)) random-state)
317 (single-float 0f0))
318 %random-single-float))
319 (defun %random-single-float (arg state)
320 (declare (type (single-float (0f0)) arg)
321 (type random-state state))
322 (* arg
323 (- (make-single-float
324 (dpb (ash (random-chunk state)
325 (- sb!vm:single-float-digits n-random-chunk-bits))
326 sb!vm:single-float-significand-byte
327 (single-float-bits 1.0)))
328 1.0)))
329 (declaim (ftype (function ((double-float (0d0)) random-state)
330 (double-float 0d0))
331 %random-double-float))
333 ;;; 32-bit version
334 #!+nil
335 (defun %random-double-float (arg state)
336 (declare (type (double-float (0d0)) arg)
337 (type random-state state))
338 (* (float (random-chunk state) 1d0) (/ 1d0 (expt 2 32))))
340 ;;; 53-bit version
341 #!-x86
342 (defun %random-double-float (arg state)
343 (declare (type (double-float (0d0)) arg)
344 (type random-state state))
345 (* arg
346 (- (sb!impl::make-double-float
347 (dpb (ash (random-chunk state)
348 (- sb!vm:double-float-digits n-random-chunk-bits 32))
349 sb!vm:double-float-significand-byte
350 (sb!impl::double-float-high-bits 1d0))
351 (random-chunk state))
352 1d0)))
354 ;;; using a faster inline VOP
355 #!+x86
356 (defun %random-double-float (arg state)
357 (declare (type (double-float (0d0)) arg)
358 (type random-state state))
359 (let ((state-vector (random-state-state state)))
360 (* arg
361 (- (sb!impl::make-double-float
362 (dpb (ash (sb!vm::random-mt19937 state-vector)
363 (- sb!vm:double-float-digits n-random-chunk-bits
364 sb!vm:n-word-bits))
365 sb!vm:double-float-significand-byte
366 (sb!impl::double-float-high-bits 1d0))
367 (sb!vm::random-mt19937 state-vector))
368 1d0))))
371 ;;;; random fixnums
373 ;;; Generate and return a pseudo random fixnum less than ARG. To achieve
374 ;;; equidistribution an accept-reject loop is used.
375 ;;; No extra effort is made to detect the case of ARG being a power of
376 ;;; two where rejection is not possible, as the cost of checking for
377 ;;; this case is the same as doing the rejection test. When ARG is
378 ;;; larger than (expt 2 N-RANDOM-CHUNK-BITS), which can only happen if
379 ;;; the random chunk size is half the word size, two random chunks are
380 ;;; used in each loop iteration, otherwise only one. Finally, the
381 ;;; rejection probability could often be reduced by not masking the
382 ;;; chunk but rejecting only values as least as large as the largest
383 ;;; multiple of ARG that fits in a chunk (or two), but this is not done
384 ;;; as the speed gains due to needing fewer loop iterations are by far
385 ;;; outweighted by the cost of the two divisions required (one to find
386 ;;; the multiplier and one to bring the result into the correct range).
387 #!-sb-fluid (declaim (inline %random-fixnum))
388 (defun %random-fixnum (arg state)
389 (declare (type (integer 1 #.sb!xc:most-positive-fixnum) arg)
390 (type random-state state))
391 (if (= arg 1)
393 (let* ((n-bits (integer-length (1- arg)))
394 (mask (1- (ash 1 n-bits))))
395 (macrolet ((accept-reject-loop (generator)
396 `(loop
397 (let ((bits (logand mask (,generator state))))
398 (when (< bits arg)
399 (return bits))))))
400 (assert (<= n-bits (* 2 n-random-chunk-bits)))
401 (if (<= n-bits n-random-chunk-bits)
402 (accept-reject-loop random-chunk)
403 (accept-reject-loop big-random-chunk))))))
405 (defun random (arg &optional (state *random-state*))
406 #!-sb-fluid (declare (inline %random-fixnum
407 %random-single-float %random-double-float
408 #!+long-float %random-long-float))
409 (declare (explicit-check))
410 (cond
411 ((and (fixnump arg) (> arg 0))
412 (%random-fixnum arg state))
413 ((and (typep arg 'single-float) (> arg 0.0f0))
414 (%random-single-float arg state))
415 ((and (typep arg 'double-float) (> arg 0.0d0))
416 (%random-double-float arg state))
417 #!+long-float
418 ((and (typep arg 'long-float) (> arg 0.0l0))
419 (%random-long-float arg state))
420 ((and (bignump arg) (> arg 0))
421 (%random-bignum arg state))
423 (error 'simple-type-error
424 :expected-type '(or (integer 1) (float (0))) :datum arg
425 :format-control "~@<Argument is neither a positive integer nor a ~
426 positive float: ~2I~_~S~:>"
427 :format-arguments (list arg)))))