为了防止2个程序从rand()生成相同的伪随机数,它们必须至少有效地为srand()使用不同的种子.
该计划的两次运行的种子来源可以来自其中之一
1) the same source – with a mechanism for unique generation.
2) a truly random source and the chance of same seed generation tolerable low.
1A#1经常使用time(),但根据定义,程序在同一秒内开始,因此简单地使用它会失败.
1B试图创建一个文件,程序访问都写“我从这个种子开始 – 12345,所以如果你再次尝试生成种子”.
1C另一种方法是使用(@Will)暗示的更精细的时间 – 这样更好,但更精细的分辨率可能还不够.
2A有些平台通过系统函数调用提供了一个真正随机的数字,但由于它依赖于各种深奥的系统事件,因此与rand()相比它很慢,但对播种srand()很有用.并非所有系统都提供此功能
[编辑]直到后来才看到Unix标签.
/ dev / random& / dev / urandom(@Dietrich Epp)提供此功能.
2B可以使用变体人类反应时间
printf("Press enter\n");
unsigned u = 0;
while (!keyboard_hit()) u++;
srand(u);
两者:组合(通过exclusive或^)各种来源,如pid(),time(),reaction_time()等有助于. (见@nodakai)
即使采用各种机制来防止随机数发生器的不同播种,2个不同的运行仍然可以产生相同的序列:每个OP代码大约1 ^ 20 ^ 10(10,240,000,000,000)次.在所有这些都是随机数之后,可能会出现相同的序列.
为了绝对防止重复,2程序必须进行通信 – 至少在一个方向上.也许哪个程序首先写入一个公共文件,生成的序列,下一个可以检查并确保它所做的序列是不同的.
// pseudo code
n = 1;
repeat {
srand(time()^n^pid());
n++;
generate_random_number_sequence();
attempt exclusive r/w access to shared file.
if (file opened) {
read file;
if (different sequence) {
write new sequence and fclose()
if (no I/O errors) {
we are done - exit
}
}
fclose()
}
maybe sleep for a fraction of a second
maybe quit if repeated too often
}