【问题标题】:Why doesn't the following code give return a probability of approximately 0.75?为什么下面的代码没有给出大约 0.75 的返回概率?
【发布时间】:2021-01-03 19:26:42
【问题描述】:

任务是模拟一对骰子的 10,000 次掷骰,并计算当我们将两个骰子的结果相乘时,其中有多少掷骰会产生偶数。这个想法是为了表明这应该非常接近理论概率 0.75。

我编写了以下代码,但是当它应该接近 7500 时,它给了我 8167 次偶数抛出。

np.random.seed(193)
#np.random.randint(0,7) is a (random) die 

count=0
for i in range(10000):
    
if np.mod(np.random.randint(0,7)*np.random.randint(0,7), 2)==0: 
        count+=1

count

(我知道有很多方法可以做到这一点,也许还有更优雅的方法,只是想看看为什么会产生这样的结果。)

【问题讨论】:

  • (0, 7) 应该是 (1, 7)。骰子上没有0
  • 你也不需要做乘法。当任一模具是偶数时,产品是偶数。
  • 您的代码正在计算两个面为 0 到 6 的 7 面骰子的结果。偶数的概率是 0.8162,所以你的结果很接近。

标签: python numpy simulation probability


【解决方案1】:

正如 cmets 中所指出的,您需要 np.random.randint(1, 7),因为骰子上没有 0

import numpy as np

np.random.seed(193)

count = 0
for i in range(10000):
    if np.mod(np.random.randint(1, 7) * np.random.randint(1, 7), 2) == 0:
        count += 1

print(count)

或者只是:

import numpy as np

np.random.seed(193)

count = sum([1 - np.mod(np.random.randint(1, 7) * np.random.randint(1, 7), 2)
             for _ in range(10000)])

print(count)

【讨论】:

    【解决方案2】:

    random.randint(0,7) 可以返回 0 或 7。需要是 random.randint(1,6)

    【讨论】:

    • random.randint 可以这样工作,但 np.random.randint 不能。他们的名字很好,不是吗? ?
    • 第二个数字是排他的。
    猜你喜欢
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多