Declare EXPLICIT-CHECK on CONCATENATE, MAKE-STRING, SET-PPRINT-DISPATCH.
[sbcl.git] / src / code / target-random.lisp
blob40d6c91f62c38d3d9d44ab42d3b5544ce470df71
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 (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 #!+sb-doc
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
95 *RANDOM-STATE*.
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)))
113 #!-win32
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.
121 (ignore-errors
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)))
126 a)))
127 (fallback-random-seed)))
129 #!+win32
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)
136 #!+sb-doc
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
142 *RANDOM-STATE*.
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) (*))
151 - UNSIGNED-BYTE
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 (named-let seed-random-state ((state state))
164 (etypecase state
165 ;; Easy standard cases
166 (null
167 (/show0 "copying *RANDOM-STATE*")
168 (%make-random-state (copy-seq (random-state-state *random-state*))))
169 (random-state
170 (/show0 "copying the provided RANDOM-STATE")
171 (%make-random-state (copy-seq (random-state-state state))))
172 ;; Standard case, less easy: try to randomly initialize a state.
173 ((eql t)
174 (/show0 "getting randomness from the operating system")
175 (seed-random-state (os-random-seed)))
176 ;; For convenience to users, we accept (simple-array (unsigned-byte 8) (*))
177 ;; We just convert it to (simple-array (unsigned-byte 32) (*)) in a
178 ;; completely straightforward way.
179 ;; TODO: probably similarly accept other word sizes.
180 ((simple-array (unsigned-byte 8) (*))
181 (/show0 "getting random seed from byte vector (converting to 32-bit-word vector)")
182 (let* ((l (length state))
183 (m (ceiling l 4))
184 (r (if (>= l 2496) 0 (mod l 4)))
185 (y (make-array (list m) :element-type '(unsigned-byte 32))))
186 (loop for i from 0 below (- m (if (zerop r) 0 1))
187 for j = (* i 4) do
188 (setf (aref y i)
189 (+ (aref state j)
190 (ash (aref state (+ j 1)) 8)
191 (ash (aref state (+ j 2)) 16)
192 (ash (aref state (+ j 3)) 24))))
193 (unless (zerop r) ;; The last word may require special treatment.
194 (let* ((p (1- m)) (q (* 4 p)))
195 (setf (aref y p)
196 (+ (aref state q)
197 (if (< 1 r) (ash (aref state (+ q 1)) 8) 0)
198 (if (= 3 r) (ash (aref state (+ q 2)) 16) 0)))))
199 (seed-random-state y)))
200 ;; Also for convenience, we accept non-negative integers as seeds.
201 ;; Small ones get passed to init-random-state, as before.
202 ((unsigned-byte 32)
203 (/show0 "getting random seed from 32-bit word")
204 (%make-random-state (init-random-state state)))
205 ;; Larger ones ones get trivially chopped into an array of (unsigned-byte 32)
206 ((unsigned-byte)
207 (/show0 "getting random seed from bignum (converting to 32-bit-word vector)")
208 (loop with l = (ceiling (integer-length state) 32)
209 with s = (make-array (list l) :element-type '(unsigned-byte 32))
210 for i below l
211 for p from 0 by 32
212 do (setf (aref s i) (ldb (byte 32 p) state))
213 finally (return (seed-random-state s))))
214 ;; Last but not least, when provided an array of 32-bit words, we truncate
215 ;; it to 19968 bits and mix these into an initial state. We reuse the same
216 ;; method as the authors of the original algorithm. See
217 ;; http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c
218 ;; NB: their mt[i] is our (aref s (+ 3 i))
219 ((simple-array (unsigned-byte 32) (*))
220 (/show0 "getting random seed from 32-bit-word vector")
221 (let ((s (init-random-state 19650218))
222 (i 1) (j 0) (l (length state)))
223 (loop for k downfrom (max mt19937-n l) above 0 do
224 (setf (aref s (+ i 3))
225 (logand #xFFFFFFFF
226 (+ (logxor (aref s (+ i 3))
227 (* 1664525
228 (logxor (aref s (+ i 2))
229 (ash (aref s (+ i 2)) -30))))
230 (aref state j) j))) ;; non-linear
231 (incf i) (when (>= i mt19937-n) (setf (aref s 3) (aref s (+ 2 mt19937-n)) i 1))
232 (incf j) (when (>= j l) (setf j 0)))
233 (loop for k downfrom (1- mt19937-n) above 0 do
234 (setf (aref s (+ i 3))
235 (logand #xFFFFFFFF
236 (- (logxor (aref s (+ i 3))
237 (* 1566083941
238 (logxor (aref s (+ i 2))
239 (ash (aref s (+ i 2)) -30))))
240 i))) ;; non-linear
241 (incf i) (when (>= i mt19937-n) (setf (aref s 3) (aref s (+ 2 mt19937-n)) i 1)))
242 (setf (aref s 3) #x80000000) ;; MSB is 1; assuring non-zero initial array
243 (%make-random-state s))))))
245 ;;;; random entries
247 ;;; This function generates a 32bit integer between 0 and #xffffffff
248 ;;; inclusive.
249 #!-sb-fluid (declaim (inline random-chunk))
250 ;;; portable implementation
251 #!-x86
252 (defun random-mt19937-update (state)
253 (declare (type random-state-state state)
254 (optimize (speed 3) (safety 0)))
255 (let ((y 0))
256 (declare (type (unsigned-byte 32) y))
257 (do ((kk 3 (1+ kk)))
258 ((>= kk (+ 3 (- mt19937-n mt19937-m))))
259 (declare (type (mod 628) kk))
260 (setf y (logior (logand (aref state kk) mt19937-upper-mask)
261 (logand (aref state (1+ kk)) mt19937-lower-mask)))
262 (setf (aref state kk) (logxor (aref state (+ kk mt19937-m))
263 (ash y -1) (aref state (logand y 1)))))
264 (do ((kk (+ (- mt19937-n mt19937-m) 3) (1+ kk)))
265 ((>= kk (+ (1- mt19937-n) 3)))
266 (declare (type (mod 628) kk))
267 (setf y (logior (logand (aref state kk) mt19937-upper-mask)
268 (logand (aref state (1+ kk)) mt19937-lower-mask)))
269 (setf (aref state kk) (logxor (aref state (+ kk (- mt19937-m mt19937-n)))
270 (ash y -1) (aref state (logand y 1)))))
271 (setf y (logior (logand (aref state (+ 3 (1- mt19937-n)))
272 mt19937-upper-mask)
273 (logand (aref state 3) mt19937-lower-mask)))
274 (setf (aref state (+ 3 (1- mt19937-n)))
275 (logxor (aref state (+ 3 (1- mt19937-m)))
276 (ash y -1) (aref state (logand y 1)))))
277 (values))
278 #!-x86
279 (defun random-chunk (state)
280 (declare (type random-state state))
281 (let* ((state (random-state-state state))
282 (k (aref state 2)))
283 (declare (type (mod 628) k))
284 (when (= k mt19937-n)
285 (random-mt19937-update state)
286 (setf k 0))
287 (setf (aref state 2) (1+ k))
288 (let ((y (aref state (+ 3 k))))
289 (declare (type (unsigned-byte 32) y))
290 (setf y (logxor y (ash y -11)))
291 (setf y (logxor y (ash (logand y (ash mt19937-b -7)) 7)))
292 (setf y (logxor y (ash (logand y (ash mt19937-c -15)) 15)))
293 (setf y (logxor y (ash y -18)))
294 y)))
296 ;;; Using inline VOP support, only available on the x86 so far.
298 ;;; FIXME: It would be nice to have some benchmark numbers on this.
299 ;;; My inclination is to get rid of the nonportable implementation
300 ;;; unless the performance difference is just enormous.
301 #!+x86
302 (defun random-chunk (state)
303 (declare (type random-state state))
304 (sb!vm::random-mt19937 (random-state-state state)))
306 #!-sb-fluid (declaim (inline big-random-chunk))
307 (defun big-random-chunk (state)
308 (declare (type random-state state))
309 (logior (ash (random-chunk state) 32)
310 (random-chunk state)))
312 ;;; Handle the single or double float case of RANDOM. We generate a
313 ;;; float between 0.0 and 1.0 by clobbering the significand of 1.0
314 ;;; with random bits, then subtracting 1.0. This hides the fact that
315 ;;; we have a hidden bit.
316 #!-sb-fluid (declaim (inline %random-single-float %random-double-float))
317 (declaim (ftype (function ((single-float (0f0)) random-state)
318 (single-float 0f0))
319 %random-single-float))
320 (defun %random-single-float (arg state)
321 (declare (type (single-float (0f0)) arg)
322 (type random-state state))
323 (* arg
324 (- (make-single-float
325 (dpb (ash (random-chunk state)
326 (- sb!vm:single-float-digits n-random-chunk-bits))
327 sb!vm:single-float-significand-byte
328 (single-float-bits 1.0)))
329 1.0)))
330 (declaim (ftype (function ((double-float (0d0)) random-state)
331 (double-float 0d0))
332 %random-double-float))
334 ;;; 32-bit version
335 #!+nil
336 (defun %random-double-float (arg state)
337 (declare (type (double-float (0d0)) arg)
338 (type random-state state))
339 (* (float (random-chunk state) 1d0) (/ 1d0 (expt 2 32))))
341 ;;; 53-bit version
342 #!-x86
343 (defun %random-double-float (arg state)
344 (declare (type (double-float (0d0)) arg)
345 (type random-state state))
346 (* arg
347 (- (sb!impl::make-double-float
348 (dpb (ash (random-chunk state)
349 (- sb!vm:double-float-digits n-random-chunk-bits 32))
350 sb!vm:double-float-significand-byte
351 (sb!impl::double-float-high-bits 1d0))
352 (random-chunk state))
353 1d0)))
355 ;;; using a faster inline VOP
356 #!+x86
357 (defun %random-double-float (arg state)
358 (declare (type (double-float (0d0)) arg)
359 (type random-state state))
360 (let ((state-vector (random-state-state state)))
361 (* arg
362 (- (sb!impl::make-double-float
363 (dpb (ash (sb!vm::random-mt19937 state-vector)
364 (- sb!vm:double-float-digits n-random-chunk-bits
365 sb!vm:n-word-bits))
366 sb!vm:double-float-significand-byte
367 (sb!impl::double-float-high-bits 1d0))
368 (sb!vm::random-mt19937 state-vector))
369 1d0))))
372 ;;;; random fixnums
374 ;;; Generate and return a pseudo random fixnum less than ARG. To achieve
375 ;;; equidistribution an accept-reject loop is used.
376 ;;; No extra effort is made to detect the case of ARG being a power of
377 ;;; two where rejection is not possible, as the cost of checking for
378 ;;; this case is the same as doing the rejection test. When ARG is
379 ;;; larger than (expt 2 N-RANDOM-CHUNK-BITS), which can only happen if
380 ;;; the random chunk size is half the word size, two random chunks are
381 ;;; used in each loop iteration, otherwise only one. Finally, the
382 ;;; rejection probability could often be reduced by not masking the
383 ;;; chunk but rejecting only values as least as large as the largest
384 ;;; multiple of ARG that fits in a chunk (or two), but this is not done
385 ;;; as the speed gains due to needing fewer loop iterations are by far
386 ;;; outweighted by the cost of the two divisions required (one to find
387 ;;; the multiplier and one to bring the result into the correct range).
388 #!-sb-fluid (declaim (inline %random-fixnum))
389 (defun %random-fixnum (arg state)
390 (declare (type (integer 1 #.sb!xc:most-positive-fixnum) arg)
391 (type random-state state))
392 (if (= arg 1)
394 (let* ((n-bits (integer-length (1- arg)))
395 (mask (1- (ash 1 n-bits))))
396 (macrolet ((accept-reject-loop (generator)
397 `(loop
398 (let ((bits (logand mask (,generator state))))
399 (when (< bits arg)
400 (return bits))))))
401 (assert (<= n-bits (* 2 n-random-chunk-bits)))
402 (if (<= n-bits n-random-chunk-bits)
403 (accept-reject-loop random-chunk)
404 (accept-reject-loop big-random-chunk))))))
406 (defun random (arg &optional (state *random-state*))
407 (declare (inline %random-fixnum %random-single-float %random-double-float
408 #!+long-float %random-long-float))
409 (cond
410 ((and (fixnump arg) (> arg 0))
411 (%random-fixnum arg state))
412 ((and (typep arg 'single-float) (> arg 0.0f0))
413 (%random-single-float arg state))
414 ((and (typep arg 'double-float) (> arg 0.0d0))
415 (%random-double-float arg state))
416 #!+long-float
417 ((and (typep arg 'long-float) (> arg 0.0l0))
418 (%random-long-float arg state))
419 ((and (bignump arg) (> arg 0))
420 (%random-bignum arg state))
422 (error 'simple-type-error
423 :expected-type '(or (integer 1) (float (0))) :datum arg
424 :format-control "~@<Argument is neither a positive integer nor a ~
425 positive float: ~2I~_~S~:>"
426 :format-arguments (list arg)))))