refactor PRINT-NOT-READABLE condition signaling
[sbcl.git] / src / code / target-random.lisp
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
8
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.
17
18 (in-package "SB!KERNEL")
19 \f
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)
28
29 ;;;; RANDOM-STATEs
30
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.
37
38 (deftype random-state-state () `(simple-array (unsigned-byte 32) (,(+ 3 mt19937-n))))
39
40 (def!method make-load-form ((random-state random-state) &optional environment)
41   (make-load-form-saving-slots random-state :environment environment))
42
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)))))
54
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))
78
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"))
84
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.
89
90   As per the Common Lisp standard,
91   - If STATE is NIL or not supplied or is NIL, 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 source where available, otherwise a poor substitute
96   based on internal time and pid)
97
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))
102
103 (defun seed-random-state (&optional state)
104   #!+sb-doc
105   "Make a random state object. The optional STATE argument specifies a seed
106   for deterministic pseudo-random number generation.
107
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
110   *RANDOM-STATE*.
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)
115
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) (*))
119   - UNSIGNED-BYTE
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.
123
124   This particular SBCL version also accepts an argument of the following type:
125   - (SIMPLE-ARRAY (UNSIGNED-BYTE 32) (*))
126
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
130 "
131   (etypecase state
132     ;; Easy standard cases
133     (null
134      (/show0 "copying *RANDOM-STATE*")
135      (%make-random-state :state (copy-seq (random-state-state *random-state*))))
136     (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.
140     ((eql t)
141      (/show0 "getting randomness from the operating system")
142      (seed-random-state
143       (or
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.
149        #!-win32
150        (ignore-errors
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)))
155              a)))
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...
158        (progn
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))
169             (m (ceiling l 4))
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))
173                for j = (* i 4) do
174                (setf (aref y i)
175                      (+ (aref state j)
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)))
181                  (setf (aref y p)
182                      (+ (aref state q)
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.
188     ((unsigned-byte 32)
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)
192     ((unsigned-byte)
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))
196        for i below l
197        for p from 0 by 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))
211                (logand #xFFFFFFFF
212                        (+ (logxor (aref s (+ i 3))
213                                   (* 1664525
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))
221                (logand #xFFFFFFFF
222                        (- (logxor (aref s (+ i 3))
223                                   (* 1566083941
224                                      (logxor (aref s (+ i 2))
225                                              (ash (aref s (+ i 2)) -30))))
226                           i))) ;; non-linear
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)))))
230 \f
231 ;;;; random entries
232
233 ;;; This function generates a 32bit integer between 0 and #xffffffff
234 ;;; inclusive.
235 #!-sb-fluid (declaim (inline random-chunk))
236 ;;; portable implementation
237 #!-x86
238 (defun random-mt19937-update (state)
239   (declare (type random-state-state state)
240            (optimize (speed 3) (safety 0)))
241   (let ((y 0))
242     (declare (type (unsigned-byte 32) y))
243     (do ((kk 3 (1+ kk)))
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)))
258                             mt19937-upper-mask)
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)))))
263   (values))
264 #!-x86
265 (defun random-chunk (state)
266   (declare (type random-state state))
267   (let* ((state (random-state-state state))
268          (k (aref state 2)))
269     (declare (type (mod 628) k))
270     (when (= k mt19937-n)
271       (random-mt19937-update state)
272       (setf k 0))
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)))
280       y)))
281
282 ;;; Using inline VOP support, only available on the x86 so far.
283 ;;;
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.
287 #!+x86
288 (defun random-chunk (state)
289   (declare (type random-state state))
290   (sb!vm::random-mt19937 (random-state-state state)))
291
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))))
298 \f
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)
305                           (single-float 0f0))
306                 %random-single-float))
307 (defun %random-single-float (arg state)
308   (declare (type (single-float (0f0)) arg)
309            (type random-state state))
310   (* arg
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)))
316         1.0)))
317 (declaim (ftype (function ((double-float (0d0)) random-state)
318                           (double-float 0d0))
319                 %random-double-float))
320
321 ;;; 32-bit version
322 #!+nil
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))))
327
328 ;;; 53-bit version
329 #!-x86
330 (defun %random-double-float (arg state)
331   (declare (type (double-float (0d0)) arg)
332            (type random-state state))
333   (* arg
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))
340         1d0)))
341
342 ;;; using a faster inline VOP
343 #!+x86
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)))
348     (* arg
349        (- (sb!impl::make-double-float
350            (dpb (ash (sb!vm::random-mt19937 state-vector)
351                      (- sb!vm:double-float-digits random-chunk-length
352                         sb!vm:n-word-bits))
353                 sb!vm:double-float-significand-byte
354                 (sb!impl::double-float-high-bits 1d0))
355            (sb!vm::random-mt19937 state-vector))
356           1d0))))
357
358 \f
359 ;;;; random integers
360
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))
368                 (- count shift)))
369         ((minusp count)
370          (rem bits arg))
371       (declare (fixnum count)))))
372
373 (defun random (arg &optional (state *random-state*))
374   (declare (inline %random-single-float %random-double-float
375                    #!+long-float %random-long-float))
376   (cond
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))
383     #!+long-float
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))
388     (t
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)))))