這是需要的代碼。注意事項如下:
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]
適當的概率值)
來源
2016-11-28 01:29:48
AER
有什麼不對的,你有什麼這麼遠嗎? –