Skip to content

Instantly share code, notes, and snippets.

@cloudwu
Last active January 30, 2023 04:29
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save cloudwu/8050870 to your computer and use it in GitHub Desktop.
Save cloudwu/8050870 to your computer and use it in GitHub Desktop.
fast IEEE 754 float random
#include <stdint.h>
#include <stdlib.h>
// assert(RAND_MAX >= 0x7fff)
float
random_0_to_1() {
union {
uint32_t d;
float f;
} u;
u.d = (((uint32_t)rand() & 0x7fff) << 8) | 0x3f800000;
return u.f - 1.0f;
}
float
random_minus1_to_1() {
union {
uint32_t d;
float f;
} u;
u.d = (((uint32_t)rand() & 0x7fff) << 8) | 0x40000000;
return u.f - 3.0f;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment