C语言中调用srand后首次rand()结果无随机性的问题排查
C语言rand()函数首次调用的随机性问题及优化
在C语言中使用rand()函数时会遇到一个问题:调用srand()初始化种子后,第一次调用rand()的结果可预测,完全没有随机性。测试时,无论是用0到10作为种子,还是用系统时间作为种子并在每次调用srand()后休眠1秒,都能观察到相似的结果——输出值和种子几乎呈线性关系。
原测试程序及输出
原程序代码
#include <string.h> #include <windows.h> #include <tchar.h> #include <time.h> #include <stdlib.h> #include <stdio.h> int main() { unsigned int randnum, ind; char line[130]; for (ind=0; ind <=10; ind++) { srand(ind); randnum = rand(); printf("%u, %u, %u, \n", ind, randnum, rand()); } gets(line); return 0; }
原程序输出
0, 38, 7719, 1, 41, 18467, 2, 45, 29216, 3, 48, 7196, 4, 51, 17945, 5, 54, 28693, 6, 58, 6673, 7, 61, 17422, 8, 64, 28170, 9, 68, 6151, 10, 71, 16899,
从输出能明显看到,种子每增加1,第一次rand()的结果就增加3或4,线性关系非常显著。
优化后的测试程序及输出
针对这个问题,修改测试逻辑:让srand()后第一次调用rand()的结果决定后续rand()的调用次数,再获取最终的随机数结果。
修改后的程序代码
#include <string.h> #include <windows.h> #include <tchar.h> #include <time.h> #include <stdlib.h> #include <stdio.h> int main() { unsigned int randnum, nreps, ind1, ind2; char line[130], ok; for (ind1=0; ind1 <=25; ind1++) { srand(ind1); nreps = rand() % 11; for (ind2=1; ind2 <= nreps; ind2++) rand (); randnum = rand(); printf("%u, %u, %u \n", ind1, nreps, randnum); } gets(line); return; }
修改后的程序输出
0, 5, 8365 1, 8, 24464 2, 1, 24198 3, 4, 23577 4, 7, 10960 5, 10, 28321 6, 3, 5206 7, 6, 11794 8, 9, 4670 9, 2, 22398 10, 5, 6722 11, 8, 28519 12, 0, 5628 13, 4, 30076 14, 7, 12236 15, 10, 28761 16, 2, 27002 17, 6, 15290 18, 9, 3191 19, 1, 209 20, 4, 24795 21, 8, 32575 22, 0, 14808 23, 3, 16714 24, 6, 27567 25, 10, 29202
从输出可以看到,修改后的结果随机性明显提升,不再呈现和种子相关的线性规律。
内容的提问来源于stack exchange,提问作者lorasaur
相关产品推荐
相关产品推荐

