This comment, which states:
srand(time(0));
I would put this line as the first line in main() instead if calling it multiple times (which will actually lead to less random numbers).
...and I've bolded the line which I'm having an issue with... repeats common advice to call srand
once in a program. Questions like srand() — why call only once? re-iterate that because time(0)
returns the current time in seconds, that multiple calls to srand
within the same second will produce the same seed. A common workaround is to use milliseconds or nanoseconds instead.
However, I don't understand why this means that srand
should or can only be called once, or how it leads to less random numbers.
Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to rand(), and the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.
phoxis's answer to srand() — why call only once?:
Initializing once the initial state with the seed value will generate enough random numbers as you do not set the internal state with srand, thus making the numbers more probable to be random.
Perhaps they're simply using imprecise language, none of the explanations seem to explain why calling srand
multiple times is bad (aside from producing the same sequence of random numbers) or how it affects the "randomness" of the numbers. Can somebody clear this up for me?
srand
for serious usage. One of it is that the distribution is biased. See e.g. eternallyconfuzzled.com/arts/jsw_art_rand.aspx for some discussion, although I remember I've seen something similar on SO, although cannot find it now. – EpidiascopeH(|X|)
, where|X|
is the size of the alphabet. – Epidiascopesrand
's sensibility to its initial seed. IMHO, it is way less important, as you can seed it only once, and not1000000
per second (in the latter case you know you get the same seed, due totime(0)
issue). The real problem inrand
is that even if you seed it once per program, your sequence is far from being random. Maybe I didn't explain the whole issue quite well, will try to improve on my answer. – Epidiascopesrand
andrand
are not the same, the former is associated solely with the seeding, and the latter with the PRNG itself. – Dilettanterand
itself. – Dilettanterand
quality is that it is not so well known, and you find code involvingrand
even in critical cryptographic components, which is a huge huge mistake. – Epidiascope