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