diff options
Diffstat (limited to 'source/kit/mersenne_twister_64.c')
-rw-r--r-- | source/kit/mersenne_twister_64.c | 37 |
1 files changed, 23 insertions, 14 deletions
diff --git a/source/kit/mersenne_twister_64.c b/source/kit/mersenne_twister_64.c index c8bbbe2..06f8535 100644 --- a/source/kit/mersenne_twister_64.c +++ b/source/kit/mersenne_twister_64.c @@ -2,6 +2,13 @@ #include "time.h" +enum { + MM = 156, + MATRIX_A = 0xb5026f5aa96619e9ull, + UM = 0xffffffff80000000ull, + LM = 0x7fffffffull +}; + void kit_mt64_init_array(kit_mt64_state_t *const state, ptrdiff_t const size, uint64_t const *const seed) { @@ -21,29 +28,26 @@ void kit_mt64_init(kit_mt64_state_t *const state, } uint64_t kit_mt64_generate(kit_mt64_state_t *const state) { - static uint64_t const mag01[2] = { 0ull, 0xB5026F5AA96619E9ull }; + static uint64_t const mag01[2] = { 0ull, MATRIX_A }; int i; uint64_t x; if (state->index >= KIT_MT64_N) { - for (i = 0; i < KIT_MT64_N - 156; i++) { - x = (state->mt[i] & 0xFFFFFFFF80000000ull) | - (state->mt[i + 1] & 0x7FFFFFFFull); - state->mt[i] = state->mt[i + 156] ^ (x >> 1u) ^ + for (i = 0; i < KIT_MT64_N - MM; i++) { + x = (state->mt[i] & UM) | (state->mt[i + 1] & LM); + state->mt[i] = state->mt[i + MM] ^ (x >> 1u) ^ mag01[(int) (x & 1ull)]; } for (; i < KIT_MT64_N - 1; i++) { - x = (state->mt[i] & 0xFFFFFFFF80000000ull) | - (state->mt[i + 1] & 0x7FFFFFFFull); - state->mt[i] = state->mt[i + (156 - KIT_MT64_N)] ^ (x >> 1u) ^ + x = (state->mt[i] & UM) | (state->mt[i + 1] & LM); + state->mt[i] = state->mt[i + (MM - KIT_MT64_N)] ^ (x >> 1u) ^ mag01[(int) (x & 1ull)]; } - x = (state->mt[KIT_MT64_N - 1] & 0xFFFFFFFF80000000ull) | - (state->mt[0] & 0x7FFFFFFFull); - state->mt[KIT_MT64_N - 1] = state->mt[156 - 1] ^ (x >> 1u) ^ + x = (state->mt[KIT_MT64_N - 1] & UM) | (state->mt[0] & LM); + state->mt[KIT_MT64_N - 1] = state->mt[MM - 1] ^ (x >> 1u) ^ mag01[(int) (x & 1ull)]; state->index = 0; @@ -52,19 +56,24 @@ uint64_t kit_mt64_generate(kit_mt64_state_t *const state) { x = state->mt[state->index++]; x ^= (x >> 29u) & 0x5555555555555555ull; - x ^= (x << 17u) & 0x71D67FFFEDA60000ull; - x ^= (x << 37u) & 0xFFF7EEE000000000ull; + x ^= (x << 17u) & 0x71d67fffeda60000ull; + x ^= (x << 37u) & 0xfff7eee000000000ull; x ^= (x >> 43u); return x; } uint64_t kit_mt64_seed() { + static uint64_t n = 0; + struct timespec t; timespec_get(&t, TIME_UTC); + uint64_t seed[2] = { (n++) ^ (uint64_t) t.tv_sec, + (uint64_t) t.tv_nsec }; + kit_mt64_state_t s; - kit_mt64_init(&s, (uint64_t) t.tv_nsec); + kit_mt64_init_array(&s, sizeof seed / sizeof *seed, seed); return kit_mt64_generate(&s); } |