Python问题我正在处理创建二项式函数的请求,需要四个输入,最后一个是true / false。如果true返回cdf,则默认为true。 if false返回pmf。这是我到目前为止所得到的。有人会告诉我如何完成代码吗?
def binomial_distribution(x,n,p,cum):
"""
Computes the probability of having x successes out of n trials.
Each trial has a probability of success p
"""
nCx = combination(n,x)
q = 1-p
return nCx*(p**x)*(q**(n-x))
答案 0 :(得分:0)
这是所需的代码。注意事项如下:
def factorial(n):
if n == 0: return 1
factrl = n
while n > 2:
n -= 1
factrl = factrl * n
return factrl
def combination(n, x):
return factorial(n)/(factorial(x)*factorial(n-x))
def binomial_distribution(x,n,p,cum = True):
"""
Computes the probability of having x successes out of n trials.
Each trial has a probability of success p
"""
nCx = combination(n,x)
q = 1-p
#What helps is a conditional return statement as below
if cum: return bin_cdf(x, n, p)
else: return nCx*(p**x)*(q**(n-x))
def bin_cdf(x, n, p):
cumul = 0.0
while x > 0:
print(x)
cumul += binomial_distribution(x, n, p, False) #Sums using formula
#This kind of recursion is not only possible but encouraged
x -= 1
return cumul
结果已使用第三方计算器验证。另请注意,它不会处理错误。好的程序还测试输入的值是否也有效(例如n
总是大于x
而p
是[0,1]
范围内的适当概率值