/* * "Cleaned up" and simplified Mersenne Twister implementation. * Vastly smaller and more easily understood and embedded. Stores the * state in a user-maintained structure instead of static memory, so * you can have more than one, or save snapshots of the RNG state. * Lacks the "init_by_array()" feature of the original code in favor * of the simpler 32 bit seed initialization. Lacks the floating * point generator, which is an orthogonal problem not related to * random number generation. Verified to be identical to the original * MT199367ar code through the first 10M generated numbers. */ #define MT_N 624 #define MT_M 397 struct mt { unsigned int array[MT_N]; int index; }; #define MT(i) mt->array[i] void mt_init(struct mt *mt, unsigned int seed) { int i; MT(0)= seed; for(i=1; i> 30)) + i); mt->index = MT_N+1; } unsigned int mt_rand32(struct mt *mt) { unsigned int i, y; if(mt->index >= MT_N) { for(i=0; i>1) ^ (y&1 ? 0x9908b0df : 0); } mt->index = 0; } y = MT(mt->index++); y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680; y ^= (y << 15) & 0xefc60000; y ^= (y >> 18); return y; } /*********************************************************************/ #include int main() { struct mt mt; mt_init(&mt, 0); while(1) printf("0x%8.8x\n", mt_rand32(&mt)); return 0; }