Skip to content

Instantly share code, notes, and snippets.

@m1lkweed
Last active September 8, 2022 04:51
Show Gist options
  • Save m1lkweed/ba6272c358bfa3cbc097f3c662184e56 to your computer and use it in GitHub Desktop.
Save m1lkweed/ba6272c358bfa3cbc097f3c662184e56 to your computer and use it in GitHub Desktop.
Generates a random-enough double in the range [0, 1)
#include <stdint.h>
static uint64_t simple_rnd_state = 0xcafef00dd15ea5e5u;
// returns a random 64-bit value
uint64_t simple_rng(void){
uint64_t x = simple_rnd_state;
simple_rnd_state = x * 6364136223846793005u;
x ^= x >> 22;
return x;
}
// initialize rng_state with a seed
void simple_rng_init(uint64_t seed){
simple_rnd_state = 2 * seed + 1;
(void)simple_rng();
}
// returns a random [0, 1) double
double rand_double(void){
const uint64_t mask = 0x000FFFFFFFFFFFFFUL;
const uint64_t sExp = 0x3FF0000000000000UL;
union{
uint64_t as_int;
double as_double;
}rnd = {
.as_int = simple_rng()
};
rnd.as_int &= mask;
rnd.as_int |= sExp;
return rnd.as_double - 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment