This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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