I have the following method which generates a random number:
int random_number() //Random number generator
{
int x = rand() % 1000000 + 1; //Generate an integer between 1 and 1000000
return x;
}
The call to this method is used in a loop which iterates five times. The problem with this method is that it always seems to generate the same numbers when running the program several times. How can this be solved?
You will notice that each time you start up a new MATLAB session, the random numbers returned by RAND are the same. This is because MATLAB's random number generator is initialized to the same state each time MATLAB starts up.
RAND returns an evenly distributed random real number greater than or equal to 0 and less than 1.
The reason is that a random number generated from the rand() function isn't actually random. It simply is a transformation.
rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.
You need to seed the random number generator, such as:
srand ( time(NULL) );
int x = rand() % 1000000 + 1;
Seeding the pseudorandom number generator essentially decides on the random number set that it will iterate through. Using the time is the standard method of achieving adequately random results.
EDIT:
To clarify, you should seed only once and get many random numbers, something like this:
srand ( time(NULL) );
loop {
int x = rand() % 1000000 + 1;
}
Rather than something like:
loop {
//Particularly bad if this line is hit multiple times in one second
srand ( time(NULL) );
int x = rand() % 1000000 + 1;
}
make a call to srand(time(NULL));
when your program launches.
srand
sets a seed to the rand function. Giving it the return value of time(NULL)
helps getting a different seed at each program run.
As you tagged your question as c++, you could either use c++11 feature to handle random number generation.
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