Randomness - widberg/fmtk GitHub Wiki
rand
microsoft.com rand
cppreference.com rand
Understanding the algorithm of Visual C++'s rand() function
Observed being called by WeatherManager_G
.
#define RAND_MAX 0x7fff
int rand() {
_ptiddata ptd = _getptd();
unsigned int r = 214013 * ptd->_holdrand + 2531011;
ptd->_holdrand = r;
return (r >> 16) & RAND_MAX;
}
Random::ran1()
Lehmer random number generator
From the book Numerical Recipes in C: The Art of Scientific Computing.
Similar to the Ran1
that appears in the Random_Z from MixedRealityToolkit/SpatialUnderstanding.
Gets called way more often than rand
.
Constants and Static State
static const int IA = 16807;
static const int IM = 0x7FFFFFFF;
static const int IQ = 127773;
static const int NTAB = 32;
static const int NDIV = (1+(IM-1)/NTAB); // 1+(0x7FFFFFFF-1)/32 = 0x4000000
static const double AM = (1.0f/IM); // 1.0f/0x7FFFFFFF = 4.6566129e-10
static const double EPS = 1.2e-7f;
static const double RNMX = (1.0f-EPS); // 0.99999988
static int idum = 0;
static int m_iY = 0;
static int m_iV[32] = {};
InitRandomSeed
Command
char CallbackInitRandomSeed() {
if (GlobalCommandManager->argc < 1 || !GlobalCommandManager->valueHasFloat[1])
return 0;
idum = (int)GlobalCommandManager->valueAsFloat[1];
if (idum >= 0)
idum = -idum;
Random_Z::ran1();
return 1;
}
Random::ran1()
double Random_Z::ran1() {
if (idum <= 0 || !m_iY) {
idum = -idum;
if (idum < 1)
idum = 1;
for (int j = NTAB + 7; j >= 0; j--) {
int k = idum / IQ;
idum = IA * idum - IM * k;
if (idum < 0)
idum += IM;
if (j < NTAB)
m_iV[j] = idum;
}
m_iY = m_iV[0];
}
int k = idum / IQ;
idum = IA * idum - IM * k;
if (idum < 0)
idum += IM;
int j = m_iY / NDIV;
m_iY = m_iV[j];
m_iV[j] = idum;
double temp = AM * m_iY;
if (temp > RNMX)
return RNMX;
return temp;
}
Random::ran2()
Usually inlined and rarely used compared to the other random functions.
Constants and Static State
static float idum2 = 0.5;
static float m_iY2 = 2.0;
Random::ran2()
double Random_Z::ran2() {
float f = (idum2 * 8.2145452 + m_iY2) * 1.4154547;
unsigned int r = *(unsigned int*)&f & 0x7FFFFF | 0x3F800000; // 1.X
return idum2 = *(float*)&r - 1.0; // 0.X
}
Random::ran3()
Constants and Static State
static unsigned int idum3 = 0;
static unsigned int m_iV3[16] = {
0xF147EB68, 0xBD4405CD, 0x0000136D, 0x990FD175,
0x09FBE6A9, 0x3D01097A, 0x8FB524CB, 0xD49E1A77,
0x3330BCA8, 0xE784C9AD, 0x1F5B734E, 0x035FA97C,
0xADB392A3, 0x57D83C79, 0x2178FE5B, 0x9B75EE37,
};
Random::ran3()
unsigned int Random_Z::ran3() {
unsigned int r = m_iV3[((unsigned char)idum3 - 3) & 0xF] ^ m_iV3[idum3] ^ ((r ^ (2 * m_iV3[idum3])) << 15);
unsigned int s = ((unsigned int)m_iV3[((unsigned char)idum3 - 7) & 0xF] >> 11) ^ m_iV3[((unsigned char)idum3 - 7) & 0xF];
m_iV3[idum3] = s ^ r;
idum3 = ((unsigned char)idum3 - 1) & 0xF;
return m_iV3[idum3] = m_iV3[idum3] ^ r ^ s ^ r ^ (32 * ((s ^ r) & 0xFED22169)) ^ (4 * (m_iV3[idum3] ^ ((r ^ (s << 10)) << 16)));
}