Friday, April 14, 2006

C++: Basic Random Numbers

Sometimes it is beneficial to generate random values in a program. This is good in cases like simulations and encryption. Someone asked me the best value to use to seed a random number generator. I don’t have a definitive answer, however I typically use the current system time to do so. After a little research, that seems to be the generally excepted standard. Srand() and rand() are pseudo random, meaning they aren’t truly random, so I don’t believe there is a “best” seed.

Here is a little bit on using random numbers in a program. Rand() is the function used in C to generate random numbers. It is defined in the Standard C Library. If the random number generator is not “seeded” with a value, it will generate the same values each time rand() is called. This is useful for developing and debugging so you can keep the same set of values with each successive call. However, in a real simulation, you may want the values to be a little more random. In which case, you will seed the random number generator with srand().

When generating random numbers, you should cap your values within an acceptable limit. For example, lets say you only need random numbers between 1 – 10. You will need to use the modulus operator with the cap value, which will return the remainder of the random value divided by the cap value. This will generate the numbers 0 – (MAX – 1), or 0 – 9 in this case. In order to get 1 through 10, you will need to add 1. Below is an example program that demonstrates using the random number generator to generate within a range of values. It will simulate 20 dice rolls with a 6-sided dice utilizing the random number generator.

#include <iostream>
#include <cstdlib> //needed for the rand function
#include <ctime> //needed to work with time

using namespace std;

int main()
     //The max random value we want generated frm the random number generator
     const unsigned char MAX_RANDOM_VALUE = 6;
     //The value to offset. rand will return values from 0 to (MAX_RANDOM_VALUE - 1)
     //so we need to offset it
     const unsigned char RANDOM_OFFSET = 1;
     int cnt; //our counter for our loop

     //We need to seed the random number generator using the current time
     //Current time is retrieved by calling time(0) OR time(NULL)
     //we will loop through 20 rolls and return our results.
     //Notice the scaleing and shifting used in the random call...
     for (cnt = 1; cnt <= 20; cnt++)
          cout << "Roll number " << cnt << ": " << RANDOM_OFFSET + (rand() % MAX_RANDOM_VALUE) << endl;
     return 0;

No comments: