randint()意外行为

时间:2015-06-14 23:32:33

标签: python math

我正在写一个python脚本来找出有关随机化的一些事情。

我有以下代码:

from random import randint

one = 0
two = 0

olddiff = 0
diff = 0

sumdiff = 0
avgdiff = 0

headcounter = 0
counter = 0


while (headcounter < 500000):
    while (counter < 500):
        x = randint(1,2)
        if(x==1):
            one += 1
        else:
            two += 1

        counter+=1

    if (one > two):
        diff = one - two
    else:
        diff = two - one

    sumdiff += diff

    if(diff > olddiff):
        olddiff = diff

    headcounter +=1


avgdiff = sumdiff / 500000


print "Occurences of 1: %d" % (one)
print "Occurences of 2: %d" % (two)
print "After 500000 calculations, the max difference found is %d" % (olddiff)
print "Sum of the differences is %d" % (sumdiff)
print "The average difference is %d" % (avgdiff)

然而,我得到了这个意想不到的输出:

首先尝试:

Occurences of 1: 262
Occurences of 2: 238
After 500000 calculations, the max difference found is 24
Sum of the differences is 24000
The average difference is 24

第二次尝试:

Occurences of 1: 247
Occurences of 2: 253
After 500000 calculations, the max difference found is 6
Sum of the differences is 3000000
The average difference is 6

第三次尝试:

Occurences of 1: 252
Occurences of 2: 248
After 500000 calculations, the max difference found is 4
Sum of the differences is 2000000
The average difference is 4

等等...

在50次运行中,最大差异与平均差异之间从来没有差别。这也是每次当前的差异。

我的代码是否有问题,或者由于randint()函数背后的机制而出现这种情况?

1 个答案:

答案 0 :(得分:1)

您永远不会重置循环中的counter,因此您只计算onetwo一次。其他499999会重复使用相同的onetwo计数,因为while (counter < 500)条件仍为False

您可以在onetwo计数中轻松查看效果;他们只加起来500。