On Mon, 04 Dec 2006 21:43:37 -0800, Markus Dehmann wrote:
According to several C++ tutorials, calling srand like this to
initialize the random number generator seems to be standard:
srand((unsigned )time(0));
But it leads to the same random number sequence on every program call
if the program is called several times in a second! Isn't there a
better method to seed the random numbers?
Yes, if you want different behavior on every run. Though you may prefer
identical behavior on every run for certain phases of testing.
Probably based on
milliseconds instead of seconds?
There isn't a standard function that's guaranteed to return milliseconds.
There's nothing in the standard that time_t can't be in milliseconds, or
that it must be. You're dealing with inherently OS-specific functionality.
And integrating the process ID or
current amount of free memory or whatever?
Is your idea that by adding PID you would get distinct sequences when the
program is run more than once in the same second? That'd probably work,
except that getting the PID is also a non-portable construct. You might
as well just used the fine-grained OS-specific time function. I know of
at least one OS in which the time function is guaranteed to return unique
values on every call. And there are OSes that don't have PIDs. So your
proposal would be unnecessary on some, and impossible on others.
Is there a C++ library that
does it right?
"Right" is a matter of opinion. IMO, a pseudo-random generator that can't
be configured to produce repeatable sequences when desired is broken. In
other words, if you want to initialize the seed from the system clock, do
so.
Here is the program that outputs 3 different random numbers on a
./a.out call, but two identical sequences if called in a row like:
./a.out; ./a.out
[...]
--
"The national budget must be balanced. The public debt must be
reduced; the arrogance of the authorities must be moderated and
controlled. Payments to foreign governments must be reduced,
if the nation doesn't want to go bankrupt. People must again
learn to work, instead of living on public assistance."
- Marcus Tullius Cicero