srand(time(NULL)) doesn’t change seed value quick enough [duplicate]

srand(time(NULL)) should be run exactly once to intialise the PRNG. Do this in Main when the application starts.

Explanation:

A PRNG (Pseudo-Random Number Generator) generates a deterministic sequence of numbers dependent on the algorithm used. A given algorithm will always produce the same sequence from a given starting point (seed). If you don’t explicitly seed the PRNG then it will usually start from the same default seed every time an application is run, resulting in the same sequence of numbers being used.

To fix this you need to seed the PRNG yourself with a different seed (to give a different sequence) each time the application is run. The usual approach is to use time(NULL) which sets the seed based on the current time. As long as you don’t start two instances of the application within a second of each other, you’ll be guaranteed a different random sequence.

There’s no need to seed the sequence each time you want a new random number. And I’m not sure about this, but I have the feeling that depending on the PRNG algorithm being used re-seeding for every new number may actually result in lower randomness in the resulting sequence.

Leave a Comment