Skip to content

Instantly share code, notes, and snippets.

@pps83
Created November 22, 2019 05:53
Show Gist options
  • Save pps83/88bfcce4d73d78d3bbde03986ad3ac13 to your computer and use it in GitHub Desktop.
Save pps83/88bfcce4d73d78d3bbde03986ad3ac13 to your computer and use it in GitHub Desktop.
pcg-based rand32() and rand64()
// pcg-based rand32() and rand64()
#include <stdint.h>
struct pcg32_random_t
{
uint64_t state;
};
static const uint64_t inc = 997;
static struct pcg32_random_t rndState = {99991};
static uint32_t pcg32_random_r(struct pcg32_random_t* rng)
{
uint64_t oldstate = rng->state;
rng->state = oldstate * 6364136223846793005ULL + (inc | 1);
uint32_t xorshifted = (uint32_t)(((oldstate >> 18u) ^ oldstate) >> 27u);
uint32_t rot = (uint32_t)(oldstate >> 59u);
return (xorshifted >> rot) | (xorshifted << ((-(int32_t)(rot)) & 31));
}
static uint32_t rand32()
{
return pcg32_random_r(&rndState);
}
static uint64_t rand64()
{
return pcg32_random_r(&rndState) | ((1ULL * pcg32_random_r(&rndState)) << 32);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment