1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien.c-types assocs byte-arrays byte-vectors
4 combinators fry io.backend io.binary kernel locals math
5 math.bitwise math.constants math.functions math.ranges
6 namespaces sequences sets summary system vocabs.loader ;
9 SYMBOL: system-random-generator
10 SYMBOL: secure-random-generator
11 SYMBOL: random-generator
13 GENERIC# seed-random 1 ( tuple seed -- tuple' )
14 GENERIC: random-32* ( tuple -- r )
15 GENERIC: random-bytes* ( n tuple -- byte-array )
17 M: object random-bytes* ( n tuple -- byte-array )
18 [ [ <byte-vector> ] keep 4 /mod ] dip
19 [ pick '[ _ random-32* 4 >le _ push-all ] times ]
22 [ 2drop ] [ random-32* 4 >le swap head append! ] if
25 M: object random-32* ( tuple -- r ) 4 swap random-bytes* le> ;
27 ERROR: no-random-number-generator ;
29 M: no-random-number-generator summary
30 drop "Random number generator is not defined." ;
32 M: f random-bytes* ( n obj -- * ) no-random-number-generator ;
34 M: f random-32* ( obj -- * ) no-random-number-generator ;
36 : random-bytes ( n -- byte-array )
37 random-generator get random-bytes* ;
41 : random-integer ( n -- n' )
43 [ random-bytes >byte-array byte-array>bignum ]
44 [ 3 shift 2^ ] bi / * >integer ;
48 : random-bits ( numbits -- r ) 2^ random-integer ;
50 : random-bits* ( numbits -- n )
51 1 - [ random-bits ] keep set-bit ;
53 GENERIC: random ( obj -- elt )
55 M: integer random [ f ] [ random-integer ] if-zero ;
59 [ length random-integer ] keep nth
62 : random-32 ( -- n ) random-generator get random-32* ;
64 : randomize-n-last ( seq n -- seq )
65 [ dup length dup ] dip - 1 max '[ dup _ > ]
66 [ [ random ] [ 1 - ] bi [ pick exchange ] keep ]
69 : randomize ( seq -- seq )
70 dup length randomize-n-last ;
72 ERROR: too-many-samples seq n ;
74 : sample ( seq n -- seq' )
75 2dup [ length ] dip < [ too-many-samples ] when
76 [ [ length iota >array ] dip [ randomize-n-last ] keep tail-slice* ]
79 : delete-random ( seq -- elt )
80 [ length random-integer ] keep [ nth ] 2keep remove-nth! drop ;
82 : with-random ( tuple quot -- )
83 random-generator swap with-variable ; inline
85 : with-system-random ( quot -- )
86 system-random-generator get swap with-random ; inline
88 : with-secure-random ( quot -- )
89 secure-random-generator get swap with-random ; inline
91 : uniform-random-float ( min max -- n )
92 4 random-bytes underlying>> *uint >float
93 4 random-bytes underlying>> *uint >float
95 [ over - 2.0 -64 ^ * ] dip
98 : normal-random-float ( mean sigma -- n )
99 0.0 1.0 uniform-random-float
100 0.0 1.0 uniform-random-float
102 [ 1.0 swap - log -2.0 * sqrt ]
106 { [ os windows? ] [ "random.windows" require ] }
107 { [ os unix? ] [ "random.unix" require ] }
110 "random.mersenne-twister" require