Skip to content

Instantly share code, notes, and snippets.

@WilliamBundy
Created June 18, 2016 15:02
Show Gist options
  • Save WilliamBundy/33b4f109638c2564b97ab0a46bfc5fc4 to your computer and use it in GitHub Desktop.
Save WilliamBundy/33b4f109638c2564b97ab0a46bfc5fc4 to your computer and use it in GitHub Desktop.
xorshift rng
#include <stdint.h>
typedef uint64_t uint64;
// Random number generators
static inline uint64 _splitmix64(uint64* x)
{
*x += UINT64_C(0x9E3779B97F4A7C15);
uint64 z = *x;
z = (z ^ (z >> 30)) * UINT64_C(0xBF58476D1CE4E5B9);
z = (z ^ (z >> 27)) * UINT64_C(0x94D049BB133111EB);
return z ^ (z >> 31);
}
static inline uint64 _rotate_left(const uint64 t, int64 k)
{
return (t << k) | (t >> (64 - k));
}
struct Random
{
uint64 x, y;
};
#define Random_Max (UINT64_MAX)
uint64 next_random_uint64(Random* r)
{
uint64 a = r->x;
uint64 b = r->y;
uint64 result = a + b;
b ^= a;
r->x = _rotate_left(a, 55) ^ b ^ (b << 14);
r->y = _rotate_left(b, 36);
return result;
}
void init_random(Random* r, uint64 seed)
{
_splitmix64(&seed);
r->x = _splitmix64(&seed);
r->y = _splitmix64(&seed);
next_random_uint64(r);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment