]> gitweb.factorcode.org Git - factor.git/blob - basis/random/random.factor
random: performance improvements to random-integer and random-bits.
[factor.git] / basis / random / random.factor
1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien.data arrays assocs byte-arrays
4 byte-vectors combinators combinators.short-circuit fry
5 hashtables hashtables.private hash-sets hints io.backend
6 io.binary kernel locals math math.bitwise math.constants
7 math.functions math.order math.ranges namespaces sequences
8 sequences.private sets summary system typed vocabs ;
9 QUALIFIED-WITH: alien.c-types c
10 QUALIFIED-WITH: sets sets
11 IN: random
12
13 SYMBOL: system-random-generator
14 SYMBOL: secure-random-generator
15 SYMBOL: random-generator
16
17 GENERIC# seed-random 1 ( tuple seed -- tuple' )
18 GENERIC: random-32* ( tuple -- r )
19 GENERIC: random-bytes* ( n tuple -- byte-array )
20
21 M: object random-bytes* ( n tuple -- byte-array )
22     [ [ <byte-vector> ] keep 4 /mod ] dip
23     [ pick '[ _ random-32* c:int <ref> _ push-all ] times ]
24     [
25         over zero?
26         [ 2drop ] [ random-32* c:int <ref> swap head append! ] if
27     ] bi-curry bi* B{ } like ;
28
29 HINTS: M\ object random-bytes* { fixnum object } ;
30
31 M: object random-32* ( tuple -- r ) 4 swap random-bytes* be> ;
32
33 ERROR: no-random-number-generator ;
34
35 M: no-random-number-generator summary
36     drop "Random number generator is not defined." ;
37
38 M: f random-bytes* ( n obj -- * ) no-random-number-generator ;
39
40 M: f random-32* ( obj -- * ) no-random-number-generator ;
41
42 : random-32 ( -- n ) random-generator get random-32* ;
43
44 TYPED: random-bytes ( n: fixnum -- byte-array: byte-array )
45     random-generator get random-bytes* ; inline
46
47 <PRIVATE
48
49 : #bits ( n -- bits )
50     dup 2 <= [ drop 1 ] [ 1 - log2 1 + ] if ; inline
51
52 :: (random-bits) ( n bits obj -- n' )
53     obj random-32* 32 bits 32 - [ dup 0 > ] [
54         [ 32 shift obj random-32* + ] [ 32 + ] [ 32 - ] tri*
55     ] while drop [ n * ] [ 2^ /i ] bi* ; inline
56
57 : (random-integer) ( n obj -- n' )
58     [ dup #bits ] dip (random-bits) ;
59
60 : random-integer ( n -- n' )
61     random-generator get (random-integer) ;
62
63 PRIVATE>
64
65 : random-bits ( numbits -- r )
66     [ 2^ ] keep random-generator get (random-bits) ;
67
68 : random-bits* ( numbits -- n )
69     1 - [ random-bits ] keep set-bit ;
70
71 GENERIC: random ( obj -- elt )
72
73 M: integer random [ f ] [ random-integer ] if-zero ;
74
75 M: sequence random
76     [ f ] [
77         [ length random-integer ] keep nth
78     ] if-empty ;
79
80 M: assoc random >alist random ;
81
82 M: hashtable random
83     dup assoc-size [ drop f ] [
84         [ 0 ] [ array>> ] [ random ] tri* 1 + [
85             [ 2dup array-nth tombstone? [ 2 + ] 2dip ] loop
86         ] times [ 2 - ] dip
87         [ array-nth ] [ [ 1 + ] dip array-nth ] 2bi 2array
88     ] if-zero ;
89
90 M: sets:set random members random ;
91
92 M: hash-set random table>> random first ;
93
94 : randomize-n-last ( seq n -- seq )
95     [ dup length dup ] dip - 1 max '[ dup _ > ]
96     [ [ random ] [ 1 - ] bi [ pick exchange-unsafe ] keep ]
97     while drop ;
98
99 : randomize ( seq -- randomized )
100     dup length randomize-n-last ;
101
102 ERROR: too-many-samples seq n ;
103
104 : sample ( seq n -- seq' )
105     2dup [ length ] dip < [ too-many-samples ] when
106     [ [ length iota >array ] dip [ randomize-n-last ] keep tail-slice* ]
107     [ drop ] 2bi nths ;
108
109 : delete-random ( seq -- elt )
110     [ length random-integer ] keep [ nth ] 2keep remove-nth! drop ;
111
112 : with-random ( tuple quot -- )
113     random-generator swap with-variable ; inline
114
115 : with-system-random ( quot -- )
116     system-random-generator get swap with-random ; inline
117
118 : with-secure-random ( quot -- )
119     secure-random-generator get swap with-random ; inline
120
121 <PRIVATE
122
123 : (uniform-random-float) ( min max obj -- n )
124     [ 4 4 ] dip [ random-bytes* c:uint deref >float ] curry bi@
125     2.0 32 ^ * +
126     [ over - 2.0 -64 ^ * ] dip
127     * + ; inline
128
129 PRIVATE>
130
131 : uniform-random-float ( min max -- n )
132     random-generator get (uniform-random-float) ; inline
133
134 M: float random [ f ] [ 0.0 swap uniform-random-float ] if-zero ;
135
136 : random-unit ( -- n )
137     0.0 1.0 uniform-random-float ; inline
138
139 : random-units ( length -- sequence )
140     random-generator get '[ 0.0 1.0 _ (uniform-random-float) ] replicate ;
141
142 : random-integers ( length n -- sequence )
143     random-generator get '[ _ _ (random-integer) ] replicate ;
144
145 : (cos-random-float) ( -- n )
146     0. 2pi uniform-random-float cos ;
147
148 : (log-sqrt-random-float) ( -- n )
149     random-unit log -2. * sqrt ;
150
151 : normal-random-float ( mean sigma -- n )
152     (cos-random-float) (log-sqrt-random-float) * * + ;
153
154 : lognormal-random-float ( mean sigma -- n )
155     normal-random-float e^ ;
156
157 : exponential-random-float ( lambda -- n )
158     random-unit log neg swap / ;
159
160 : weibull-random-float ( alpha beta -- n )
161     [
162         [ random-unit log neg ] dip
163         1. swap / ^
164     ] dip * ;
165
166 : pareto-random-float ( k alpha -- n )
167     [ random-unit ] dip recip ^ /f ;
168
169 :: (gamma-random-float>1) ( alpha beta -- n )
170     ! Uses R.C.H. Cheng, "The generation of Gamma
171     ! variables with non-integral shape parameters",
172     ! Applied Statistics, (1977), 26, No. 1, p71-74
173     2. alpha * 1 - sqrt :> ainv
174     alpha 4. log -      :> bbb
175     alpha ainv +        :> ccc
176
177     0 :> r! 0 :> z! 0 :> result! ! initialize locals
178     [
179         r {
180             [ 1. 4.5 log + + z 4.5 * - 0 >= ]
181             [ z log >= ]
182         } 1|| not
183     ] [
184         random-unit :> u1
185         random-unit :> u2
186
187         u1 1. u1 - / log ainv / :> v
188         alpha v e^ *           :> x
189         u1 sq u2 *              z!
190         bbb ccc v * + x -       r!
191
192         x beta *                result!
193     ] do while result ;
194
195 : (gamma-random-float=1) ( alpha beta -- n )
196     nip random-unit log neg * ;
197
198 :: (gamma-random-float<1) ( alpha beta -- n )
199     ! Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
200     alpha e + e / :> b
201
202     0 :> x! 0 :> p! ! initialize locals
203     [
204         p 1.0 > [
205             random-unit x alpha 1 - ^ >
206         ] [
207             random-unit x neg e^ >
208         ] if
209     ] [
210         random-unit b * p!
211         p 1.0 <= [
212             p 1. alpha / ^
213         ] [
214             b p - alpha / log neg
215         ] if x!
216     ] do while x beta * ;
217
218 : gamma-random-float ( alpha beta -- n )
219     {
220         { [ over 1 > ] [ (gamma-random-float>1) ] }
221         { [ over 1 = ] [ (gamma-random-float=1) ] }
222         [ (gamma-random-float<1) ]
223     } cond ;
224
225 : beta-random-float ( alpha beta -- n )
226     [ 1. gamma-random-float ] dip over zero?
227     [ 2drop 0 ] [ 1. gamma-random-float dupd + / ] if ;
228
229 :: von-mises-random-float ( mu kappa -- n )
230     ! Based upon an algorithm published in: Fisher, N.I.,
231     ! "Statistical Analysis of Circular Data", Cambridge
232     ! University Press, 1993.
233     kappa 1e-6 <= [
234         2pi random-unit *
235     ] [
236         4. kappa sq * 1. + sqrt 1. + :> a
237         a 2. a * sqrt - 2. kappa * / :> b
238         b sq 1. + 2. b * /           :> r
239
240         0 :> c! 0 :> _f! ! initialize locals
241         [
242             random-unit {
243                 [ 2. c - c * < ] [ 1. c - e^ c * <= ]
244             } 1|| not
245         ] [
246             random-unit pi * cos :> z
247             r z * 1. + r z + /   _f!
248             r _f - kappa *       c!
249         ] do while
250
251         mu 2pi mod _f cos random-unit 0.5 > [ + ] [ - ] if
252     ] if ;
253
254 :: (triangular-random-float) ( low high mode -- n )
255     mode low - high low - / :> c!
256     random-unit :> u!
257     high low
258     u c > [ 1. u - u! 1. c - c! swap ] when
259     [ - u c * sqrt * ] keep + ;
260
261 : triangular-random-float ( low high -- n )
262     2dup + 2 /f (triangular-random-float) ;
263
264 : laplace-random-float ( mean scale -- n )
265     random-unit dup 0.5 <
266     [ 2 * log ] [ 1 swap - 2 * log neg ] if * + ;
267
268 : cauchy-random-float ( median scale -- n )
269     random-unit 0.5 - pi * tan * + ;
270
271 : chi-square-random-float ( dof -- n )
272     [ 0.5 ] dip 2 * gamma-random-float ;
273
274 : student-t-random-float ( dof -- n )
275     [ 0 1 normal-random-float ] dip
276     [ chi-square-random-float ] [ / ] bi sqrt / ;
277
278 : inv-gamma-random-float ( shape scale -- n )
279     recip gamma-random-float recip ;
280
281 : rayleigh-random-float ( mode -- n )
282     random-unit log -2 * sqrt * ;
283
284 : gumbel-random-float ( loc scale -- n )
285     random-unit log neg log * - ;
286
287 : logistic-random-float ( loc scale -- n )
288     random-unit dup 1 swap - / log * + ;
289
290 : power-random-float ( alpha -- n )
291     [ random-unit log e^ 1 swap - ] dip recip ^ ;
292
293 ! Box-Muller
294 : poisson-random-float ( mean -- n )
295     [ -1 0 ] dip
296     [ 2dup < ]
297     [ [ 1 + ] 2dip [ random-unit log neg + ] dip ] while 2drop ;
298
299 {
300     { [ os windows? ] [ "random.windows" require ] }
301     { [ os unix? ] [ "random.unix" require ] }
302 } cond
303
304 "random.mersenne-twister" require