尝试为您的随机数生成器选择不同的种子值。虽然rand()是一个相当好的随机数生成器,但实际上它是伪随机数生成器。您可能需要阅读rand的man页面(man -s3 rand),其中清楚地说明您应该(对于某些实现)使用高位比低位。
NOTES
The versions of rand() and srand() in the Linux C Library use the same
random number generator as random(3) and srandom(3), so the lower-order
bits should be as random as the higher-order bits. However, on older
rand() implementations, and on current implementations on different
systems, the lower-order bits are much less random than the higher-
order bits. Do not use this function in applications intended to be
portable when good randomness is needed. (Use random(3) instead.)
如果我们不了解您正在运行程序的系统,就无法确定那是否是您的问题。但是请尝试更改您的代码,使用不同于2^0位的位。
我成功地运行了您的版本。
/coinflipsim
Ran 100000000 times
head 50006650, streak 27
tail 49993350, streak 25
这是一段对我有效的代码,使用的是比0位不同的位。
int main(int argc, char const *argv[])
{
srand(time(0));
int i, lim = 100000000;
int head=0, tail=0;
int hstreak=0, tstreak=0;
int hstreakmax=0, tstreakmax=0;
for (i = 0; i < lim; ++i)
{
if( rand() & (1<<13) )
{
head++;
if( ++hstreak>hstreakmax) hstreakmax=hstreak;
tstreak=0;
}
else {
tail++;
if( ++tstreak>tstreakmax) tstreakmax=tstreak;
hstreak=0;
}
}
printf("Ran %d times\n",lim);
printf("head %d, streak %d\n",head,hstreakmax);
printf("tail %d, streak %d\n",tail,tstreakmax);
return 0;
}
将rand()%2行改为以下内容并重新运行:
if( rand() & (1<<13) ) //pick a bit, try different bits
不同的结果,
./coinflipsim
Ran 100000000 times
head 50001852, streak 25
tail 49998148, streak 28
rand()
存在偏差。 - chux - Reinstate Monicaif ((rand()%2) == 0)
会得到什么结果? - chux - Reinstate Monica