1 ! Copyright (C) 2005, 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 ! mersenne twister based on
4 ! http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c
5 USING: kernel math namespaces sequences sequences.private system
6 init accessors math.ranges random math.bitwise combinators
7 specialized-arrays.uint fry ;
8 IN: random.mersenne-twister
12 TUPLE: mersenne-twister { seq uint-array } { i fixnum } ;
16 : a uint-array{ 0 HEX: 9908b0df } ; inline
19 [ nth-unsafe 31 mask-bit ]
20 [ [ 1+ ] [ nth-unsafe ] bi* 31 bits ] 2bi bitor ; inline
22 : mt[k] ( offset n seq -- )
24 [ [ + ] dip nth-unsafe ]
25 [ y [ 2/ ] [ 1 bitand a nth ] bi bitxor ] 2bi
27 ] 2keep set-nth-unsafe ; inline
29 : mt-generate ( mt -- )
32 [ [ n m - ] dip '[ [ m ] dip _ mt[k] ] each ]
33 [ [ m 1- ] dip '[ [ m n - ] [ n m - + ] bi* _ mt[k] ] each ]
35 ] [ 0 >>i drop ] bi ; inline
37 : init-mt-formula ( i seq -- f(seq[i]) )
38 dupd nth dup -30 shift bitxor 1812433253 * + 1+ 32 bits ; inline
40 : init-mt-rest ( seq -- )
42 _ [ init-mt-formula ] [ [ 1+ ] dip set-nth ] 2bi
45 : init-mt-seq ( seed -- seq )
46 32 bits n <uint-array>
47 [ set-first ] [ init-mt-rest ] [ ] tri ; inline
49 : mt-temper ( y -- yt )
51 dup 7 shift HEX: 9d2c5680 bitand bitxor
52 dup 15 shift HEX: efc60000 bitand bitxor
53 dup -18 shift bitxor ; inline
55 : next-index ( mt -- i )
56 dup i>> dup n < [ nip ] [ drop mt-generate 0 ] if ; inline
60 : <mersenne-twister> ( seed -- obj )
61 init-mt-seq 0 mersenne-twister boa
64 M: mersenne-twister seed-random ( mt seed -- )
65 init-mt-seq >>seq drop ;
67 M: mersenne-twister random-32* ( mt -- r )
69 [ seq>> nth-unsafe mt-temper ]
70 [ [ 1+ ] change-i drop ] tri ;
75 [ 32 random-bits ] with-system-random
76 <mersenne-twister> random-generator set-global
77 ] "bootstrap.random" add-init-hook