Why does rand() yield the same sequence of numbers on every run?

The seed for the random number generator is not set.

If you call srand((unsigned int)time(NULL)) then you will get more random results:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    srand((unsigned int)time(NULL));
    cout << rand() << endl;
    return 0;
}

The reason is that a random number generated from the rand() function isn’t actually random. It simply is a transformation. Wikipedia gives a better explanation of the meaning of pseudorandom number generator: deterministic random bit generator. Every time you call rand() it takes the seed and/or the last random number(s) generated (the C standard doesn’t specify the algorithm used, though C++11 has facilities for specifying some popular algorithms), runs a mathematical operation on those numbers, and returns the result. So if the seed state is the same each time (as it is if you don’t call srand with a truly random number), then you will always get the same ‘random’ numbers out.

If you want to know more, you can read the following:

http://www.dreamincode.net/forums/topic/24225-random-number-generation-102/

http://www.dreamincode.net/forums/topic/29294-making-pseudo-random-number-generators-more-random/

Leave a Comment