我需要一种“好的”方法来初始化 C++ 中的伪随机数生成器。我找到了an article说明:
In order to generate random-like numbers, srand is usually initialized to some distinctive value, like those related with the execution time. For example, the value returned by the function time (declared in header ctime) is different each second, which is distinctive enough for most randoming needs.
Unixtime 对我的应用程序来说不够独特。初始化它的更好方法是什么?如果它是可移植的,则加分,但代码将主要在 Linux 主机上运行。
我正在考虑做一些 pid/unixtime 数学来获得一个 int,或者可能从 /dev/urandom
读取数据。
谢谢!
编辑
是的,我实际上是在每秒多次启动我的应用程序并且遇到了冲突。
最佳答案
这是我用于可以频繁运行的小型命令行程序(每秒多次):
unsigned long seed = mix(clock(), time(NULL), getpid());
混合在哪里:
// Robert Jenkins' 96 bit Mix Function
unsigned long mix(unsigned long a, unsigned long b, unsigned long c)
{
a=a-b; a=a-c; a=a^(c >> 13);
b=b-c; b=b-a; b=b^(a << 8);
c=c-a; c=c-b; c=c^(b >> 13);
a=a-b; a=a-c; a=a^(c >> 12);
b=b-c; b=b-a; b=b^(a << 16);
c=c-a; c=c-b; c=c^(b >> 5);
a=a-b; a=a-c; a=a^(c >> 3);
b=b-c; b=b-a; b=b^(a << 10);
c=c-a; c=c-b; c=c^(b >> 15);
return c;
}
关于c++ - 初始化 srand 的推荐方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/322938/