问题
How can I create two independent random number generators (without the necessity for being cryptographically secure) in C on 64bit Debian Linux, using gcc 7.2.0?
One of both RNGs should offer random numbers seed using srand(time(NULL));
, while the other should be initialized using a commandline parameter for creating reproducible experiments.
Below example will seed the same RNG with two different values, how will this work having two different possible rand()
calls?
#include <stdlib.h>
#include <time.h>
int main(int argc, char**argv)
{
// seed first RNG
srand(time(NULL));
// seed second RNG
srand(argv[1]);
// use both RNGs in production code for
// different purposes ...
return 0;
}
The purpose of this is, that I use one RNG for generating problem instances on the fly, which should be the same over all experiment runs, therefore following the same seed on all program restarts. The second RNG is used by the algorithm, which requires a (Pseudo) RNG differing on each program execution.
回答1:
rand
is not a good tool for the task.
Since you are on a POSIX system, you should better look into the drand48
family of functions. These have variants that allow you to specify the seed vector as function arguments, e.g erand48
. With them you can just have two different seed vectors and call the function with the one to your liking.
来源:https://stackoverflow.com/questions/48171737/create-two-differently-seeded-independent-rng-in-c