Python程序,计算一次滚动12次时,至少获得1两次的概率

时间:2018-09-28 06:03:31

标签: python python-3.x probability

import random
import sys

bestcounter1 = 0
bestcounter2=0
get_sample = int(sys.argv[1])

for i in range(get_sample):
    for i in range(12):
        if (random.randint(1,6)==1):
            bestcounter1+=1
            bestcounter2+=1

oneatleasttwice = (bestcounter2*1.0)/(2*(get_sample))

#Divide by 2 to make both comparable. Otherwise 2 will always be greater than 1 !
print("One atleast twice in 12 rolls: ", oneatleasttwice)

有人可以解释这里使用的逻辑是否正确吗?我得到的输出总是在1左右。

谢谢

1 个答案:

答案 0 :(得分:1)

您必须将柜台放在正确的位置。假设bestcounter1用于在每次运行(12卷)期间对1的值进行计数,而bestcounter2用于在具有2个或更多值1的情况下对运行进行计数。那么您的main for循环应如下所示:

for i in range(get_sample):
    # reset before every run
    bestcounter1 = 0
    for i in range(12):
        if random.randint(1, 6) == 1:
            # count values of 1
            bestcounter1 += 1
        # check if we got 2 or more values of 1
        if bestcounter1 >= 2:
            # count proper cases
            bestcounter2 += 1
            break

oneatleasttwice = bestcounter2 / get_sample

一百万次跑步我得到61.9%的结果。