为什么总数不到1000?

时间:2017-06-27 13:18:01

标签: python random simulation

当我运行下面的程序时,总数不是1000.我不知道出了什么问题。

在1000次掷骰子中,有:

  • 180 for 1
  • 136 for 2
  • 121 for 3
  • 97 for 4
  • 72 for 5
  • 60 for 6。

总共有666卷骰子。

我想具体说明,如果有什么我不清楚的地方,请告诉我。谢谢大家:)

#this is a program that simulate how many times that there will be for every sides of a dice, when I trying to throw it 1,000 times.

from random import randrange

def toss():
    if randrange(6) == 0:
        return "1"
    elif randrange(6) ==1:
        return "2"
    elif randrange(6) ==2:
        return "3"
    elif randrange(6) ==3:
        return "4"
    elif randrange(6) ==4:
        return "5"
    elif randrange(6) ==5:
        return "6"

def roll_dice(n):
    count1 = 0
    count2 = 0
    count3 = 0
    count4 = 0
    count5 = 0
    count6 = 0
    for i in range(n):
        dice = toss()
        if dice == "1":
            count1 = count1 + 1
        if dice == "2":
            count2 = count2 + 1
        if dice == "3":
            count3 = count3 + 1
        if dice =="4":
            count4 = count4 + 1
        if dice == "5":
            count5 = count5 + 1
        if dice == "6":
            count6 = count6 + 1
    print ("In", n, "tosses of a dice, there were", count1, "for 1 and", 

count2, "for 2 and", count3, "for 3 and", count4, "for 4 and", count5, "for
 5 and",count6, "for 6.")

roll_dice(1000)

2 个答案:

答案 0 :(得分:6)

您在所有randrange(6)测试中都在调用if/elif,因此价值不同(随机),您最终可能会返回来自None函数的toss(并且您错过了一些计数)

randrange(6)存储在变量中,然后对其进行测试。

有更好的方法来做这个BTW,例如一个等效的但是有效的:

def toss():
    return str(randrange(6)+1)

但是使用collections.Counter和生成器理解可以更快捷地从1到6随机生成1000个值:

import collections
import random
c = collections.Counter(random.randint(1,6) for _ in range(1000))
print(c)
print(sum(c.values()))

我得到那两条输出线(首先是dict计算数字和滚动总数):

Counter({3: 199, 2: 172, 1: 160, 5: 160, 4: 158, 6: 151})
1000

现在我有1000个值:)

答案 1 :(得分:1)

因为它在每种情况下都会再次调用该函数。

if randrange(6) == 0:

如果它不为0则继续到第二个if,其中randrange(6)将再次以新值调用。