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