Click to See Complete Forum and Search --> : C++ Random Number: Why does my random number generator always return the same set?


KevinHall
February 27th, 2004, 06:36 PM
Q: Why does my random number generator always return the same set?

A: A random number generator needs to be seeded before use, or it will always generate the same list of random numbers. For example the C 'time()' function can be used for this:


srand(time(NULL));

One should generally avoid using 'clock()' to initialize random numbers, since 'clock()' returns the amount of time the current thread has been running, generally a number close to zero.

Good seeds will involve more "random" bits. One way this can be accomplished is by using higher resolution timers such as a performance counter or an RDTSC value. Better seeds may mix the least significant bits of different timers. The best seeds are produced from truely random sources. If a computer is connected to the internet, truely random seeds can be obtained from sites like random.org (http://www.random.org).
<br><br>