72 const MTRand::uint32 MTRand::state_size;
74 MTRand MTRand::instance;
76 static const MTRand::uint32 period = 397;
77 static const MTRand::uint32 MATRIX_A = 0x9908b0df;
78 static const MTRand::uint32 UPPER_MASK = 0x80000000;
79 static const MTRand::uint32 LOWER_MASK = 0x7fffffff;
82 static MTRand::uint32 hash( time_t t, clock_t c )
88 typedef MTRand::uint32 uint32;
91 static uint32 differ = 0;
94 auto *p = (
unsigned char *) &t;
95 for(
size_t i = 0; i <
sizeof(t); ++i )
101 p = (
unsigned char *) &c;
102 for(
size_t j = 0; j <
sizeof(c); ++j )
104 h2 *= UCHAR_MAX + 2U;
107 return ( h1 + differ++ ) ^ h2;
114 FILE* urandom = fopen(
"/dev/urandom",
"rb" );
117 uint32 init_vector[state_size];
118 uint32 *s = init_vector;
121 while( success && i-- )
122 success = fread( s++,
sizeof(uint32), 1, urandom );
124 if( success ) { seed( init_vector, state_size );
return; }
128 seed( hash( time(
nullptr), clock() ) );
132 void MTRand::seed(uint32 s)
135 for (index = 1; index < state_size; ++index)
137 state[index] = (1812433253UL * (state[index-1] ^ (state[index-1] >> 30u)) + index);
142 void MTRand::seed(
const uint32 init_vector[],
const uint32 init_vector_length)
147 uint32 k = (state_size > init_vector_length ? state_size : init_vector_length);
150 state[i] ^= ((state[i-1] ^ (state[i-1] >> 30u)) * 1664525UL);
151 state[i] += (init_vector[j] & 0xffffffffUL) + j;
153 if (i >= state_size) { state[0] = state[state_size-1]; i = 1; }
154 if (j >= init_vector_length) j = 0;
156 for (k = state_size - 1; k; --k)
158 state[i] ^= ((state[i-1] ^ (state[i-1] >> 30u)) * 1566083941UL);
161 if (i >= state_size) { state[0] = state[state_size-1]; i = 1; }
163 state[0] = 0x80000000UL;
167 MTRand::uint32 MTRand::randInt()
170 static unsigned long mag01[2]={0x0UL, MATRIX_A};
173 if (index >= state_size)
176 for (kk=0; kk < state_size - period; kk++)
178 y = (state[kk]&UPPER_MASK) | (state[kk+1]&LOWER_MASK);
179 state[kk] = state[kk + period] ^ (y >> 1u) ^ mag01[y & 0x01u];
181 for (; kk < state_size-1; kk++)
183 y = (state[kk]&UPPER_MASK) | (state[kk+1]&LOWER_MASK);
184 state[kk] = state[kk+(period - state_size)] ^ (y >> 1u) ^ mag01[y & 0x01u];
186 y = (state[state_size-1]&UPPER_MASK) | (state[0]&LOWER_MASK);
187 state[state_size-1] = state[period-1] ^ (y >> 1u) ^ mag01[y & 0x1UL];
196 y ^= (y << 7u) & 0x9d2c5680UL;
197 y ^= (y << 15u) & 0xefc60000UL;
204 std::ostream& MTRand::save(std::ostream& ostr)
const
210 return ostr << index;
214 std::istream& MTRand::load(std::istream& istr)
216 for (
auto & i : state)
Generic library namespace.