/*Copyright (c) 2004 Nils O. Selåsdal */ /*Straight forward attempt at a Mersenne Twister PRNG */ #include "ucore/mersenne_twister.h" /*Beware , pollution. But the names are from the spec */ enum { N = MT_RAND_N, w = 32, M = 387, R = 19, U = 0x80000000, LL= 0x7FFFFFFF, a = 0x9908B0DF, s = 7, t = 15, b = 0x9D2C5680, c = 0xEFC60000, l = 18, u = 11, }; void mtsrand(int seed, MTRand *r) { int j; for (j = 0 ; j < N ; j++) { r->x[j] = seed * ((j+1)<< 3)|0x1; } r->i = 0; } unsigned int mtrand(MTRand *r) { unsigned int y; unsigned int ch[] = {0, a}; y = r->x[r->i] & U; y |= r->x[r->i % N]; y &= LL; r->x[r->i] = r->x[(r->i + M ) %N]; r->x[r->i] ^= y >> 1; r->x[r->i] ^= ch[y&0x1]; y = r->x[r->i]; y ^= y >> u; y ^= (y << s) & b; y ^= (y << t) & c; y ^= y >> l; r->i = (r->i + 1) % N; return y; } #ifdef TEST_MT #include #include int main(int argc,char *argv[]) { MTRand r; mtsrand(time(NULL),&r); for (;;){ unsigned int _y = mtrand(&r); if (_y < 100) printf("%u \n",_y); } return 0; } #endif