Skip to content

Instantly share code, notes, and snippets.

@corsix

corsix/rand.c Secret

Last active October 17, 2023 11:46
Show Gist options
  • Save corsix/c21d715238e32ce6d44a7fc1b44f427d to your computer and use it in GitHub Desktop.
Save corsix/c21d715238e32ce6d44a7fc1b44f427d to your computer and use it in GitHub Desktop.
/* See: https://mumble.net/~campbell/2014/04/28/uniform-random-float */
/* See: https://allendowney.com/research/rand/downey07randfloat.pdf */
double randf_3a() {
double d;
uint64_t u = rand_next();
uint64_t exp = __builtin_ctzll(u | (1 << 12)) - 1022ull;
u = (((u >> 11) + 1) >> 1) - (exp << 52);
memcpy(&d, &u, sizeof(d));
return d;
}
double randf_3b() {
double d;
uint64_t u = rand_next();
uint64_t exp = __builtin_ctzll(u) - 11ull;
if ((int64_t)exp >= 0) exp = __builtin_ctzll(rand_next());
u = (((u >> 11) + 1) >> 1) - ((exp - 1011ull) << 52);
memcpy(&d, &u, sizeof(d));
return d;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment