Skip to content

Instantly share code, notes, and snippets.

@seanofw
Last active Feb 1, 2021
Embed
What would you like to do?
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