Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rand() always returns the same sequence on application restart

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?

like image 861
Matthew Avatar asked Nov 07 '12 16:11

Matthew


People also ask

Why does rand always return the same number?

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.

What possible values does rand () return?

RAND returns an evenly distributed random real number greater than or equal to 0 and less than 1.

Why is rand giving me the same number in C++?

The reason is that a random number generated from the rand() function isn't actually random. It simply is a transformation.

What is the use of rand () function?

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.


2 Answers

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;
}
like image 80
femtoRgon Avatar answered Oct 04 '22 19:10

femtoRgon


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.

like image 34
tomahh Avatar answered Oct 04 '22 18:10

tomahh