I am using srand((unsigned)time(NULL))
to seed the randomizer in my C program. I noticed that when I create an array of random numbers using loops, all of the numbers will be the same if I put the seeder inside the loop instead of outside the loop. I assume this is because the loop runs extremely fast, but how does the seeder work to reseed the randomizer when it is outside of the loop? I am confused about how this is working in the program.

- 11
- 2
2 Answers
You should only srand
once in your program.
Because time(NULL)
is measured in seconds, inside a loop you are actually seeding the same value over and over.
Each seed will produce a deterministic stream of pseudo-random numbers, but setting the same seed twice produces the same sequence twice.
About srand
:
http://www.cplusplus.com/reference/cstdlib/srand/
About time
: https://www.tutorialspoint.com/c_standard_library/c_function_time.htm
Why once: srand() — why call it only once?

- 730,956
- 141
- 904
- 1,278

- 1,280
- 9
- 14
-
1You can also xor with the pid to add a bit more "randomness" to the seed – Ed Heal Jul 22 '17 at 22:09
-
1Also, it is good to output the seed to a log, so bugs can be reproduced – Yuval Ben-Arie Jul 22 '17 at 22:14
Using srand((unsigned)time(NULL))
to seed the random number generator is not reliable as time()
returns the number of seconds since Jan 1st, 1970. This value only changes every second. If you re-seed the generator during the same second, you will indeed get the same random sequence again.
You should use a source that changes faster:
srand((unsigned)clock());
Furthermore, re-seeding the generator is not recommended. The pseudo random number generator is crafted to produce a random sequence with certain properties. re-seeding the generator breaks this promise.

- 131,814
- 10
- 121
- 189