C++ random numbers

11,902

Regarding the srand(), one item that I don't think has been explained - for a given seed, you will always get the same random sequence (not just srand(0)). Because the time(0) function is changes every second, it is not likely that the seed will be the same from run to run, which is why it is often used with srand().

Think of the random number generator as a complicated mathematical expression with a single input. Every time you call it, it uses the previous output as then input to generate the next number. The results are predictable, if your input is 5 and you get 10 one time, you'll get it the next time, too. So unless you want to use the same random sequence every run (sometimes not a bad thing!), you want to set the first input (the seed) to something (somewhat) random, such as the current time.

Caveat: random number generators internally use a much larger number than the one they output, so the input/output relationship is not usually as straightforward as the '5 gets you 10' in the example. But the idea is the same.

Share:
11,902
Simplicity
Author by

Simplicity

Updated on June 06, 2022

Comments

  • Simplicity
    Simplicity almost 2 years

    At the following: http://www.fredosaurus.com/notes-cpp/misc/random.html

    It mentions that if we want to generate a random number in the range 1-10, we can do the following:

    r = (rand() % 10) + 1;

    Why do we add 1? Can you just explain how the process works?

    And, regarding initializing the random number generator, it mentioned doing the following:

    srand(time(0));

    Can you explain this process? And, what happens if we don't initialize at all?

    Thanks.