即使是种子,C中的rand()函数也不是随机的 [英] rand() function in C is not random even when seeded
问题描述
这很可能是与机器有关的问题,但我不知道可能出了什么问题.
This is most likely a machine dependent issue but I can't figure out what could be wrong.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char** argv) {
srand(time(NULL));
int r1 = rand();
int r2 = rand();
printf("%d %d\n", r1, r2);
}
我使用以下代码编译以上代码
I compile the above piece of code using
gcc randd.c
然后手动运行几次,第一个数字看起来非常相似,而第二个数字似乎是随机的:
Then running it a few times manually and the first numbers seem incredibly similar while the second ones seem random:
1025720610 1435057801
1025737417 1717533050
1025754224 2000008299
1025771031 134999901
1025787838 417475150
第一次调用rand()
似乎与时间密切相关,并且随着时间的推移严格增加.关于为什么会发生或如何解决的任何想法?
This first call to rand()
seems strongly co-related to the time and is strictly increasing as time passes. Any ideas as to why this occurs or how to resolve it?
这在OSX 10.11上发生
This happens on OSX 10.11
推荐答案
-
rand()
非常差,请尽可能避免.在任何好的RNG中,即使种子接近(汉明距离),第一个值也不会与随机值区分开.在rand
中不是这种情况. - 如果必须使用rand,则最好以比时间高的熵来播种它,并多次调用
rand()
而不是reseeding-calling-reseeding.
rand()
is quite bad, avoid it if possible. In any good RNG the first values will be indistinguishable from random even when the seed is close (hamming distance). Inrand
this is not the case.- If you must use rand then seed it, preferably with something higher entropy than time, and call
rand()
multiple times instead of reseeding-calling-reseeding.
以2为例,请考虑:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char** argv) {
int t=time(NULL);
srand(t);
for(int i=0; i < 10; i++) {
float r = (float)rand()/(float)(RAND_MAX);
printf("%f\n", r);
}
}
结果:
0.460600
0.310486
0.339473
0.519799
0.258825
0.072276
0.749423
0.552250
0.665374
0.939103
它仍然是一个不良的RNG,但是如果允许它使用内部状态而不是给它另一个相似的种子,则至少范围更好.
It's still a bad RNG but at least the range is better when you allow it to use the internal state instead of giving it another similar seed.
这篇关于即使是种子,C中的rand()函数也不是随机的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!