random.mersenne-twister: more complete fix for bias.

db4
John Benediktsson 2014-02-07 11:56:29 -08:00
parent 0110bd49f1
commit d9961f5f4a
1 changed files with 14 additions and 14 deletions

View File

@ -2,9 +2,9 @@
! See http://factorcode.org/license.txt for BSD license. ! See http://factorcode.org/license.txt for BSD license.
! mersenne twister based on ! mersenne twister based on
! http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c ! http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c
USING: alien.c-types alien.data kernel math namespaces sequences USING: accessors alien.c-types alien.data fry init kernel math
sequences.private system init accessors math.ranges random math.bitwise namespaces random sequences sequences.private
math.bitwise combinators specialized-arrays fry ; specialized-arrays ;
SPECIALIZED-ARRAY: uint SPECIALIZED-ARRAY: uint
IN: random.mersenne-twister IN: random.mersenne-twister
@ -16,23 +16,23 @@ CONSTANT: n 624
CONSTANT: m 397 CONSTANT: m 397
CONSTANT: a uint-array{ 0 0x9908b0df } CONSTANT: a uint-array{ 0 0x9908b0df }
: y ( n seq -- y ) : mt-step ( k+m k+1 k seq -- )
[ nth-unsafe 31 mask-bit ]
[ [ 1 + ] [ nth-unsafe ] bi* 31 bits ] 2bi bitor ; inline
: mt[k] ( offset n seq -- )
[ [
[ [ + ] dip nth-unsafe ] [ nth-unsafe ] curry tri@
[ y [ 2/ ] [ 1 bitand a nth ] bi bitxor ] 2bi [ 31 bits ] [ 31 mask-bit ] bi* bitor
bitxor [ 2/ ] [ 1 bitand a nth ] bi bitxor bitxor
] 2keep set-nth-unsafe ; inline ] 2keep set-nth-unsafe ; inline
: mt-steps ( k k+1 k+m n seq -- )
[ mt-step ] curry [ 3keep [ 1 + ] tri@ ] curry times 3drop ; inline
: mt-generate ( mt -- ) : mt-generate ( mt -- )
[ [
seq>> seq>>
[ [ n m - ] dip '[ [ m ] dip _ mt[k] ] each-integer ] [ [ m 1 0 n m - ] dip mt-steps ]
[ [ m ] dip '[ [ m n - ] [ n m - + ] bi* _ mt[k] ] each-integer ] [ [ 0 n m - 1 + n m - m 1 - ] dip mt-steps ]
bi [ [ m 1 - 0 n 1 - ] dip mt-step ]
tri
] [ 0 >>i drop ] bi ; inline ] [ 0 >>i drop ] bi ; inline
: init-mt-formula ( i seq -- f(seq[i]) ) : init-mt-formula ( i seq -- f(seq[i]) )