In C/C++, rand()
and srand()
are usually used by us when we want to get a random integer. But when I tried to rewrite it myself, I found it difficult to understand the algorithm. The function is very easily written in only a few lines, but the formula is misunderstanding.
The main formula:
ptd->_holdrand = ptd->_holdrand * 214013L + 2531011L;
The original code involved:
void __cdecl srand (unsigned int seed)
{
_getptd()->_holdrand = (unsigned long)seed;
}
int __cdecl rand (void)
{
_ptiddata ptd = _getptd();
return ( ((ptd->_holdrand = ptd->_holdrand * 214013L + 2531011L) >> 16) & 0x7fff );
}
The rand() function is used in C++ to generate random numbers in the range [0, RAND_MAX) Note: If random numbers are generated with rand() without first calling srand(), your program will create the same sequence of numbers each time it runs. Syntax: int rand(void):
Explanation : rand() generate random number between the wide range of 0 to RAND_MAX.
The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.
C++ has a std::rand() function from cstdlib library that generates a random number.
It's just modular arithmetic. You're multiplying and adding to a number which is taken modulo 2^32 (for example), and returning the upper 16 bit as your "random" number. Because you're multiplying and adding numbers which are coprime to the modulus, this creates sort of uniformly distributed numbers.
The careful choice of the two numbers is very important. For example, if you had used "* 4" and "+ 8", you would probably not experience a lot of randomness.
This scheme is called linear congruential.
That pseudorandom number generator is a Linear Congruential Generator.
You can find an explanation of the Linear Congruential Generator (LCG) and other similar families or pseudo random generators, and about the selection of these specific constants in an excellent article published this month (7-2011) in Dr. Dobb's Journal (DDJ): Fast, High-Quality, Parallel Random-Number Generators: Comparing Implementations.
I think you'll need to register at DDJ's website (free) to read the first part of this article (link), but if you're into C++ and mathematics you should do it anyway...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With