Skip to content

Instantly share code, notes, and snippets.

@seanofw
Last active February 1, 2021 01:43
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 seanofw/34937a65571a4cff63f0d6f1618dcef7 to your computer and use it in GitHub Desktop.
Save seanofw/34937a65571a4cff63f0d6f1618dcef7 to your computer and use it in GitHub Desktop.
private static volatile int RandomSeed = 1;
private static int FastRand()
{
retry:
int oldSeed = RandomSeed;
int newSeed = unchecked(oldSeed * 1103515245 + 12345);
if (Interlocked.CompareExchange(ref RandomSeed, newSeed, oldSeed) != oldSeed)
goto retry;
int rand = (newSeed >> 16) & 0x7FFF;
return rand;
}
public static float FloatRand()
{
int bits = (FastRand() | (FastRand() << 15)) & 0xFFFFFF;
if (bits == 0) return 0;
int exp = 127;
if ((bits & 0xFFF000) == 0) { bits <<= 12; exp -= 12; }
if ((bits & 0xF30000) == 0) { bits <<= 6; exp -= 6; }
if ((bits & 0xE00000) == 0) { bits <<= 3; exp -= 3; }
if ((bits & 0xC00000) == 0) { bits <<= 2; exp -= 2; }
if ((bits & 0x800000) == 0) { bits <<= 1; exp -= 1; }
bits |= (exp << 24);
unsafe
{
return *(float *)&bits;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment