为什么下面的代码没有给出 return 大约 0.75 的概率?
Why doesn't the following code give return a probability of approximately 0.75?
任务是模拟掷一对骰子 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
(我知道有很多方法可以做到这一点,也许还有更优雅的方法,只是想看看为什么会产生这样的结果。)
random.randint(0,7) 可以 return 0 或 7。需要是 random.randint(1,6)
正如评论中指出的那样,您想要 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)
任务是模拟掷一对骰子 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
(我知道有很多方法可以做到这一点,也许还有更优雅的方法,只是想看看为什么会产生这样的结果。)
random.randint(0,7) 可以 return 0 或 7。需要是 random.randint(1,6)
正如评论中指出的那样,您想要 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)