XorshiftアルゴリズムとはXORとシフトだけで品質の良い疑似乱数を生成するアルゴリズム。
// 周期 (2^32 - 1) 版 Xorshiftアルゴリズム #include <stdint.h> static uint32_t x = 2463534242; void xorshift32_seed(uint32_t seed) { if (seed != 0){ x = seed; } } uint32_t xorshift32(void) { x ^= (x << 13); x ^= (x >> 17); x ^= (x << 15); return x; }
// 周期 (2^128 - 1) 版 Xorshiftアルゴリズム #include <stdint.h> static uint32_t x = 123456789; static uint32_t y = 362436069; static uint32_t z = 521288629; static uint32_t w = 88675123; void xorshift128_seed(uint32_t seed) { if (seed != 0){ x = y = z = w = seed; } } uint32_t xorshift128(void) { uint32_t t; t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); return w; }