C++: Using the rand() Function
Using the rand() Function
In this C++ tutorial, we explain how to use the rand() function to generate random numbers. To be precise, the function rand() only generates pseudo-random numbers. However, we are unlikely to find a truly random source anyway, and this function should be suitable for most purposes. That said, we also explain a bit about the method of generating numbers with rand(). The video shows the linear congruential method, which is a simplified version of what rand() actually generates. The actual rand() function probably looks something like this, along with srand() and RAND_MAX:
The actual function used to generate random numbers is not nearly as important at this point as understanding the fact that pseudo-random number generators generate a fixed, periodic sequence of numbers. The video shows how we seed the random number generator, by using the time() function and the srand() seeding function. Using the time to seed the generator ensures that we generate a new sequence of numbers whenever the program is run.
The numbers generated by rand() run from 0 to RAND_MAX, where RAND_MAX is a C++ defined constant. Typically, RAND_MAX equals 32767, but that value may be different on some systems. We mentioned that we could set our range of values to something smaller by using the modulus operator. For example, we could simulate a roulette wheel (single zero version) with this function:
However, unless the modulus divides RAND_MAX + 1 evenly, we will not get a perfectly uniform distribution. In fact, the smaller numbers will be favored slightly. Usually, this would not be a problem, but in a gambling program it definitely would, since the odds are only slightly in favor of the casinos. To fix this, we could write our function to throw out the numbers above the final multiple. In this case, all numbers greater than or equal to (RAND_MAX / 36) * 36 should be discarded.
As a side note, this point about distributions is not simply academic. Two great mathematical minds, Ed Thorpe and Claude Shannon, once went to Las Vegas to beat the casinos at Roulette by gaining a very slight advantage in the numerical distribution. Ed Thorpe then went on to devise a system for beating casinos at Blackjack by counting cards. His system eventually caused casinos to reevaluate and change their gaming rules; he has since moved onto bigger games, like investing in the stock market.