Skip to content

Instantly share code, notes, and snippets.

@gpakosz
Created November 8, 2018 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gpakosz/dbc597cc47b7b07b98f39967a3c9cf2a to your computer and use it in GitHub Desktop.
Save gpakosz/dbc597cc47b7b07b98f39967a3c9cf2a to your computer and use it in GitHub Desktop.
PCG32 based floating point random number generation
/**
* Generates a pseudorandom number, in the [0, 1[ interval.
* @param rng Pointer to the pseudorandom number generator.
*/
static inline float rand_f(pcg32_random_t* rng)
{
const uint32_t max = 1 << 24;
uint32_t r = pcg32_random_r(rng);
r &= max - 1;
return r * 1.0f / max;
}
/**
* Generates a pseudorandom number, in the [0, 1[ interval, rounded to the
* nearest multiple of 1/2^32.
* @param rng Pointer to the pseudorandom number generator.
*/
static inline double rand_d32(pcg32_random_t* rng)
{
union rand_double_t
{
uint64_t u;
double d;
};
union rand_double_t u = { 0x3df0000000000000 }; // ldexp(1, -32);
uint32_t r = pcg32_random_r(rng);
return (double)r * u.d;
}
/**
* Generates a pseudorandom number, in the [0, 1[ interval, rounded to the
* nearest multiple of 1/2^64.
* @param rng Pointer to the pseudorandom number generator.
*/
static inline double rand_d64(pcg32_random_t* rng)
{
union rand_double_t
{
uint64_t u;
double d;
};
union rand_double_t u = { 0x3bf0000000000000 }; // ldexp(1, -64);
uint64_t r = (uint64_t)pcg32_random_r(rng) << 32;
pcg32_random_t rng_ = *rng;
pcg32_random_t.inc += 2;
r |= pcg32_random_r(&rng_);
return (double)r * u.d;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment