Skip to content

Instantly share code, notes, and snippets.

@vtta
Created December 15, 2023 10:36
Show Gist options
  • Save vtta/09da12c3c17e67dc05e2cf1fcb48931f to your computer and use it in GitHub Desktop.
Save vtta/09da12c3c17e67dc05e2cf1fcb48931f to your computer and use it in GitHub Desktop.
// clang-format off
u64 mt19937_u64(void)
{
#define NN 312
#define MM 156
#define MATRIX_A 0xB5026F5AA96619E9ULL
// Most significant 33 bits
#define UM 0xFFFFFFFF80000000ULL
// Least significant 31 bits
#define LM 0x7FFFFFFFULL
static u64 mag01[2] = { 0ULL, MATRIX_A };
// The array for the state vector
static u64 mt[NN];
// mti==NN+1 means mt[NN] is not initialized
static int mti = NN + 1;
if (mti >= NN) {
// generate NN words at one time
// if init_genrand64() has not been called,
// a default initial seed 5489ULL is used
if (mti == NN + 1) {
mt[0] = 0x990124ULL;
for (mti = 1; mti < NN; mti++) {
mt[mti] = 6364136223846793005ULL * (mt[mti - 1] ^ (mt[mti - 1] >> 62)) + mti;
}
}
for (int i = 0; i < NN - MM; i++) {
u64 x = (mt[i] & UM) | (mt[i + 1] & LM);
mt[i] = mt[i + MM] ^ (x >> 1) ^ mag01[x & 1ULL];
}
for (int i = NN - MM; i < NN - 1; i++) {
u64 x = (mt[i] & UM) | (mt[i + 1] & LM);
mt[i] = mt[i + (MM - NN)] ^ (x >> 1) ^ mag01[x & 1ULL];
}
u64 x = (mt[NN - 1] & UM) | (mt[0] & LM);
mt[NN - 1] = mt[MM - 1] ^ (x >> 1) ^ mag01[x & 1ULL];
mti = 0;
}
u64 x = mt[mti++];
x ^= (x >> 29) & 0x5555555555555555ULL; x ^= (x << 17) & 0x71D67FFFEDA60000ULL;
x ^= (x << 37) & 0xFFF7EEE000000000ULL; x ^= (x >> 43);
return x;
}
// clang-format on
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment