我对python比较陌生,正在自学。我想出了一个挑战来提高我的技能:写一个泊松概率计算器。在
我一共写了3个函数。第一:单个离散变量的泊松概率。第二:从0开始的累积泊松概率。第三:闭合区间内的累积泊松概率。在
不知何故,前两个函数工作得很好,但最后一个函数(称为第二个函数)非常接近,但不是真的。在
我用了以下数学方法:
泊松分布:
累积泊松分布:
区间概率:
下面是我的源代码:
from math import exp, factorial
def poissonpdf(mean, discvar):
"""Returns Poisson probability based on mean and a discreet random variable.
:param mean: float
:param discvar: positive integer or 0
:return: float between 0 and 1
"""
usage = 'Usage: poisson(mean, discreet random variable)'
# if type(discvar) != int or discvar < 0:
# print 'ERR: discreet random variable value invalid.'
# print usage
# return None
# if type(mean) != int or float:
# print 'ERR: mean value invalid.'
# print usage
# return None
probability = (mean**discvar * exp(-mean)) / float(factorial(discvar))
return probability
def poissoncdf(mean, k):
"""Returns cumulative Poisson probability until k.
:param mean: float
:param k: integer
:return: float between 0 and 1
"""
cumulative = 0.0
i = 0
while i <= k:
cumulative += (mean ** i) / float(factorial(i))
i += 1
cumulative *= exp(-mean)
return cumulative
def poissoncdfinterval(mean, lower, upper):
"""Returns cumulative Poisson probability based on mean and a range of discreet random variables.
Including lower bound and excluding upper.
:param mean: float
:param lower: positive integer or 0
:param upper: positive integer or 0
:return: float between 0 and 1
"""
usage = 'Usage: poisson(mean, discreet random variable, number of iterations)'
# if type(mean) != float or type(mean) != int:
# print 'ERR: mean value invalid.'
# print usage
# return None
# if type(lower) != int or lower < 0 or type(upper) != int or upper < 0:
# print 'ERR: invalid interval.'
# print usage
# return None
probability = poissoncdf(mean, upper) - poissoncdf(mean, lower)
return probability
print 'PoissonPdf mean=4, X=2:', poissonpdf(4, 2) #works
print
print 'PoisoonCdf mean=4, from 0 to 2:', poissoncdf(4, 2) #works
print
print 'PosiionCdf on interval from 2,4 with mean 4:', poissoncdfinterval(4, 2, 4) #close...
我知道第三个函数不包括上界。在
欢迎对我的PEP用法进行任何更正,并改进我的语法。在
结果证明我的功能是正确的。我没有意识到我包括了上限,排除了下限,而不是相反。在
我改了这条线:
为此:
^{pr2}$现在这两个边界都应该包括在内。在
是的,就这样。在
相关问题 更多 >
编程相关推荐