【问题标题】:Rolling 2 dice 1000 times and counting the number of times the sum of the two dice hit掷 2 个骰子 1000 次并计算两个骰子的总和命中次数
【发布时间】:2020-06-06 04:45:06
【问题描述】:

作业要求我们通过实验找出 2 到 12 的概率作为总和。我们想掷两个骰子 1000 次,并计算总和为 2、3、……和 12 的次数。到目前为止,我将其作为我的代码,但我无法获得教授要求的输出。

到目前为止我所拥有的:

import random as r

die_1 = r.randint(1,6)
die_2 = r.randint(1,6)


print('For-Loop')
for i in range(2,13):
    r.seed(1)
    counter = 0
    for j in range(1000):
        if i == r.randint(2,12):
            counter = counter + 1
    print("sum = ", i,  " count = ",  counter)

【问题讨论】:

  • 你掷骰子11 * 1000 次。没什么大不了的,但你的描述不同。
  • @finefoot 并不意味着链接到图像 - 他/她的意思是将代码粘贴到问题的正文中please
  • 你没有说她在找什么,但概率在 0 到 1 的范围内,所以也许只需将你的值除以所有值的总和
  • 但我无法得到教授要求的输出。这是什么意思?
  • @AMC 我添加了示例输出的图片

标签: python arrays for-loop dice


【解决方案1】:
from random import randint

rolls = [sum([randint(1, 6), randint(1, 6)]) for i in range(1000)]

for i in range(2, 13):
    print(f'Sum of {i} was rolled {rolls.count(i)} times')

【讨论】:

  • 二项式定理
【解决方案2】:

我试图解释 cmets 中发生的一切:

from collections import defaultdict
from random import randint

# Roll the two dice how many times?
n = 1000

# Create a dictionary to store the results
results = defaultdict(int)

# Loop n times
for _ in range(n):
    # Get random numbers for the two dice
    die_1 = randint(1, 6)
    die_2 = randint(1, 6)
    # Increase the corresponding result by 1
    results[die_1 + die_2] += 1

# Print results
print(results)

可能会打印出这样的内容:

defaultdict(<class 'int'>, {7: 160, 8: 134, 6: 145, 9: 107, 3: 50, 10: 76, 12: 26, 4: 86, 5: 128, 2: 37, 11: 51})

您还可以用图表轻松地说明结果:

import matplotlib.pyplot as plt
plt.bar(results.keys(), results.values())
plt.show()

【讨论】:

  • 如果你想知道为什么这个图看起来像这个 OP,两个不错的分布的卷积是 niceN(\mu, \sigma)它们中最好的 i> - 甚至是离散的 ;)
【解决方案3】:

您没有正确计算概率。 r.randint(2, 12) 与独立掷两个骰子不同(因为它们是两个骰子的多个掷骰子,对于某些值来说,总和相同)。

import collections
import random

print("For Loop")

occurrences = []
for trial in range(1000):
    die1 = random.randint(1, 6)
    die2 = random.randing(1, 6)
    occurrences.append(die1 + die2)
counter = collections.Counter(occurrences)
for roll, count in counter.items():
    print(f"sum = {roll} count = {count}") 

如果您不想导入标准库的其他部分,您可以自己制作计数器。

import random

print("For Loop")
occurrences = {}
for trial in range(1000):
    die1 = random.randint(1, 6)
    die2 = random.randing(1, 6)
    roll = die1 + die2
    current = occurrences.setdefault(roll, 0)
    occurrences[roll] = current + 1

for roll, count in occurrences.items():
    print(f"sum = {roll} count = {count}")

请注意,输出会略有不同,因为它们当然涉及随机性。

【讨论】:

    猜你喜欢
    • 2018-12-17
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多