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