2016-11-27 80 views
0

我正在處理創建二項函數的請求,需要四個輸入,最後一個是真/假。如果爲true,則返回cdf,默認爲true。如果false返回pmf。這是我到目前爲止。有人會告訴我如何完成代碼?二項分佈式輸出使用Python的CDF/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)) 
+2

有什麼不對的,你有什麼這麼遠嗎? –

回答

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總是比xp更大的範圍內[0,1]適當的概率值)