1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien.c-types arrays assocs byte-arrays
4 byte-vectors combinators fry io.backend io.binary kernel locals
5 math math.bitwise math.constants math.functions math.order
6 math.ranges namespaces sequences sets summary system
10 SYMBOL: system-random-generator
11 SYMBOL: secure-random-generator
12 SYMBOL: random-generator
14 GENERIC# seed-random 1 ( tuple seed -- tuple' )
15 GENERIC: random-32* ( tuple -- r )
16 GENERIC: random-bytes* ( n tuple -- byte-array )
18 M: object random-bytes* ( n tuple -- byte-array )
19 [ [ <byte-vector> ] keep 4 /mod ] dip
20 [ pick '[ _ random-32* 4 >le _ push-all ] times ]
23 [ 2drop ] [ random-32* 4 >le swap head append! ] if
26 M: object random-32* ( tuple -- r ) 4 swap random-bytes* le> ;
28 ERROR: no-random-number-generator ;
30 M: no-random-number-generator summary
31 drop "Random number generator is not defined." ;
33 M: f random-bytes* ( n obj -- * ) no-random-number-generator ;
35 M: f random-32* ( obj -- * ) no-random-number-generator ;
37 : random-bytes ( n -- byte-array )
38 random-generator get random-bytes* ;
42 : random-integer ( n -- n' )
44 [ random-bytes >byte-array byte-array>bignum ]
45 [ 3 shift 2^ ] bi / * >integer ;
49 : random-bits ( numbits -- r ) 2^ random-integer ;
51 : random-bits* ( numbits -- n )
52 1 - [ random-bits ] keep set-bit ;
54 GENERIC: random ( obj -- elt )
56 M: integer random [ f ] [ random-integer ] if-zero ;
60 [ length random-integer ] keep nth
63 : random-32 ( -- n ) random-generator get random-32* ;
65 : randomize-n-last ( seq n -- seq )
66 [ dup length dup ] dip - 1 max '[ dup _ > ]
67 [ [ random ] [ 1 - ] bi [ pick exchange ] keep ]
70 : randomize ( seq -- randomized )
71 dup length randomize-n-last ;
73 ERROR: too-many-samples seq n ;
75 : sample ( seq n -- seq' )
76 2dup [ length ] dip < [ too-many-samples ] when
77 [ [ length iota >array ] dip [ randomize-n-last ] keep tail-slice* ]
80 : delete-random ( seq -- elt )
81 [ length random-integer ] keep [ nth ] 2keep remove-nth! drop ;
83 : with-random ( tuple quot -- )
84 random-generator swap with-variable ; inline
86 : with-system-random ( quot -- )
87 system-random-generator get swap with-random ; inline
89 : with-secure-random ( quot -- )
90 secure-random-generator get swap with-random ; inline
92 : uniform-random-float ( min max -- n )
93 4 random-bytes underlying>> *uint >float
94 4 random-bytes underlying>> *uint >float
96 [ over - 2.0 -64 ^ * ] dip
99 : normal-random-float ( mean sigma -- n )
100 0.0 1.0 uniform-random-float
101 0.0 1.0 uniform-random-float
103 [ 1.0 swap - log -2.0 * sqrt ]
107 { [ os windows? ] [ "random.windows" require ] }
108 { [ os unix? ] [ "random.unix" require ] }
111 "random.mersenne-twister" require