尝试为您的随机数生成器选择不同的种子值。尽管 rand() 是一个非常好的随机数生成器,但它确实是一个伪随机数生成器。您可能想阅读 rand (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()%2)
if( rand() & (1<<13) ) //pick a bit, try different bits
{
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