Python概率

问题描述 投票:3回答:6

我们有一个六面模具,边数为1到6.第一次看到第1卷的1的概率随着n的增加而减小。我想找到最小数量的卷,这样这个概率小于某个给定的限制。

def probTest(limit):
    prob = 1.0
    n = 1
    while prob > limit:
        prob = (1/6)**n
        n += 1        
    return n-1

我的代码出了什么问题?

python math probability
6个回答
7
投票

在第n卷上滚动一个的概率是5/6 ^(n-1)* 1/6,而不是1/6 ^ n。 1/6 ^ n是在所有n个辊上滚动一个的概率。

前n-1卷每个都有5/6的机会不成为一个。 第n卷有1/6的机会成为一个。


2
投票

正确的将是:prob =(5.0 / 6)**(n-1)* 1 / 6.0


1
投票

谢谢。请考虑其他因素。

probTest(25 / 216.0)返回4而不是正确的结果n = 3


0
投票

伯努利试验的数量X的概率分布需要得到一次成功,遵循几何分布(https://en.wikipedia.org/wiki/Geometric_distribution),我们可以使用以下公式直接给出X=n计算相应的概率p

p = 1./6 # prob of successes
geom_prob = []
for n in range(1,25):
    geom_prob.append((1-p)**(n-1)*p) 
print geom_prob 
# [0.16666666666666666, 0.1388888888888889, 0.11574074074074076, 0.09645061728395063, 0.08037551440329219, 0.06697959533607684, 0.05581632944673069, 0.04651360787227558, 0.038761339893562986, 0.032301116577969156, 0.02691759714830763, 0.022431330956923026, 0.018692775797435855, 0.015577313164529882, 0.012981094303774901, 0.010817578586479085, 0.009014648822065905, 0.0075122073517215875, 0.006260172793101323, 0.005216810660917769, 0.0043473422174314744, 0.003622785181192896, 0.0030189876509940797, 0.002515823042495067]
import matplotlib.pyplot as plt
plt.plot(geom_prob)
plt.xlabel('n')
plt.ylabel('probability')
plt.title('Probability of getting first head on nth roll of a die')
plt.show()

enter image description here

我们也可以使用模拟来查找概率,如下所示:

import numpy as np
sim_geom = np.random.geometric(p=p, size=1000)
import seaborn as sns   
sns.distplot(sim_geom)
plt.show()

enter image description here


-1
投票
def probTest(limit):
    prob = 1.0
    n = 1
    while prob > limit:
        prob =  5/6^(n-1)*1/6.0
        n += 1        
    return n

-1
投票
def probTest(limit):
    n=1
    prob = 1.0
    while prob > limit:
        prob = prob * (1/6.0)*((5/6.0)**n-1)
        n +=1
    return n-1
© www.soinside.com 2019 - 2024. All rights reserved.