Intiha wrote:
Hello all,
I am trying to generate random seeds for my simulations.
currently i was using srand(time(NULL); for this purpose.
But for confidence in my results i ran it using a script in a loop.
Since the time b/w execution is very similar, many simulation runs
resulted in exact same results.
Is there a better way of seeding the random number generator in c/c++
than time(NULL).
If you want different outputs, you need different inputs.
In your case, I'd suggest modifying your script so that it
provides a different command-line argument to your program each
time around the loop: "myprog 1", "myprog 2", ... Hash this
value with the time() result so the srand() argument will be
different even if time() doesn't change from one run to the
next. Note that the hash should not be something simple like
`time(NULL) ^ cmdarg', because a small change in time() could
be cancelled by a small change in cmdarg -- do something more
"pervasive," like using cmdarg as the initial value of `seed'
in the randomize() function you quoted.
Some systems provide sources of "truly random" (whatever
that means) numbers, often through a special file name like
/dev/random. These sources are usually slow and hence not a
substitute for rand(), but they provide a good way to get an
srand() argument that's suitably unpredictable. Unfortunately,
such things are not part of C itself, and they way they're
provided (if they're provided) varies from system to system.
Consult your documentation.
Finally, I note that if time() returns the same value at
the start of "many" runs, then your simulation program probably
doesn't run very long. Instead of running the whole program
over and over, struggling with ways to get different srand()
seeds each time, consider rearranging your program so it runs
many simulations each time it executes. Call srand() once at
the beginning of this "super-program," and then just let the
repeated "internal" simulations keep on calling rand().
Old:
int main(void) {
srand(...);
simulate();
return 0;
}
New:
int main(void) {
int run;
srand(...);
for (run = 0; run < 100; ++run)
simulate();
return 0;
}
--
Eric Sosman
es*****@acm-dot-org.invalid