网上都说(int)(rand()*N/(RAND_MAX+1.0))产生的随机数比(int)(rand()%N)更随机,但是好像前者产生随机数的奇偶性
不怎么样,下面是我测试N=2是,产生随机数的结果。
测试代码如下,不知道为什么,当Sleep为5000的时候(rand()*N/(RAND_MAX+1.0))生成的随机数就是0101010101的,总的来说,
(int)(rand()%N)产生的随机数让我找不到规律,(rand()*N/(RAND_MAX+1.0))产生的总是几个挨在一起的就一样,出来我设置
Sleep(5000)的时候变成101010,但这个也是规律的。对于随机数来说是不是说(int)(rand()%N)更稳定些呢,简单记录一下。
for (int ii = 0;ii < 1000;++ii)
{
srand((unsigned)GetCurrentTime());
//int tmp=(int)(rand()*2/(RAND_MAX+1.0));
int tmp = (int)(rand()%2);
std::cout<<tmp<<" ";
Sleep(10000);
}
int tmp=(int)(rand()*2/(RAND_MAX+1.0)); 1000ms
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0
0 1 1 1 1 1 0 0 0 0 0 1 1 1 1
int tmp = (int)(rand()%2); 1000ms
1 0 1 0 0 1 1 0 0 0 1 0 0 1 0 1 0 1 1 1
1 0 1 1 0 1 0 1 0 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