繁体   English   中英

掷 2 个骰子 1000 次并计算两个骰子命中的次数

[英]Rolling 2 dice 1000 times and counting the number of times the sum of the two dice hit

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

到目前为止我所拥有的:

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)
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')

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

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()

在此处输入图片说明

您没有正确考虑概率。 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}")

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM