Anonymous user
Random Number Generator: Difference between revisions
→Mersenne Twister: Replace implementation
[unchecked revision] | [unchecked revision] |
(→Wichmann-Hill: Link the original paper) |
(→Mersenne Twister: Replace implementation) |
||
Line 187:
The Mersenne Twister is an incredibly popular PRNG and is available on most platforms; for example, it is part of the set of generators required by the C++11 standard library. An implementation of the 64-bit MT-19937 version in C is as follows:
Implementation according to Wikipedia:
<source lang="c">▼
▲<source lang="c">
#include <stddef.h>
#include <stdint.h>
#include <assert.h>
#ifdef USE32
#define W 64▼
typedef uint32_t word_t;
#define N 312▼
#define
#define
#define INIT_SHIFT 30
#define INIT_FACT 1812433253
#define TWIST_MASK 0x9908b0df
#define SHIFT1 11
#define MASK1 0xffffffff
#define MASK2 0x9d2c5680
#define SHIFT3 15
#define MASK3 0xefc60000
#define SHIFT4 18
#else
typedef uint64_t word_t;
#define MIDDLE 156
#define TWIST_MASK 0xb5026f5aa96619e9
#define MASK1 0x5555555555555555
#define MASK2 0x71d67fffeda60000
#define SHIFT3 37
#define MASK3 0xfff7eee000000000
#define SHIFT4 43
#endif
#define
#define
static word_t state[STATE_SIZE];
▲#define S 17
▲#define T 37
▲#define L 43
▲#define F 6364136223846793005
{
index = STATE_SIZE;
}▼
static
{
▲static unsigned int index = N + 1;
▲static void mt_twist(void) {
▲ for (unsigned int i = 0; i < N; ++i) {
if (x & 1) {▼
▲ state[i] = state[(i + M) % N] ^ xa;
}
index = 0;
}
static word_t mt_random(void)
{
▲ state[0] = seed;
if (index >=
▲ for (unsigned int i = 1; i < N; ++i) {
assert(index == STATE_SIZE || !"Generator never seeded");
▲ state[i] = F * (state[i - 1] ^ (state[i - 1] >> (W - 2))) + i;
}
▲}
word_t y = state[index];
y
y ^= (y << SHIFT3) &
y ^= y >>
▲ }
}</source>▼
Some implementations automatically seed the generator with seed 5489, but this will (obviously) lead to the same outputs at every initialization.
▲</source>
It outperforms all PRNGs listed above, but it is rather slow due to its large state size. It also has problems in some statistical areas. See [https://arxiv.org/abs/1910.06437 "It is high time we let go of the Mersenne Twister"].
|