2016-09-26 23 views
1

我試圖寫一個函數來計算使用這個公式二項式係數計算二項式係數時:enter image description here回答錯誤使用改良式

我遇到的問題是,我不能疥癬,以得到正確的答案。這是我試圖編寫函數的兩種方法的一個例子。

def binomial(n, i): 
    total = 0 

    for j in range(1, (n-i+1)): 
     n = float(n) 
     i = float(i) 
     j = float(j)   

     product = (i+j)/j 

     if total == 0: 
      total = product 
     else: 
      total = total * product 

    print '%.f' %total 

或像這樣使用numpy的

的功能
import numpy as np 

def binomial_np(n, i): 
    array = np.zeros(n-i+1) 

    for j in range(1, (n-i+1)): 
     s = float(j) 
     n = float(n) 
     i = float(i) 

     array[j] = (i+s)/s 

    array = array[1 : ] 
    array = np.prod(array)  

    print '%.f' %array 

兩者產生幾乎正確的結果。環顧了一下在論壇上我也發現,確實產生正確的結果,這樣一個從Python Binomial Coefficient

import math 
x = int(input("Enter a value for x: ")) 
y = int(input("Enter a value for y: ")) 
if y == x: 
    print(1) 
elif y == 1:   # see georg's comment 
    print(x) 
elif y > x:   # will be executed only if y != 1 and y != x 
    print(0) 
else:    # will be executed only if y != 1 and y != x and x <= y 
    a = math.factorial(x) 
    b = math.factorial(y) 
    c = math.factorial(x-y) # that appears to be useful to get the correct result 
    div = a // (b * c) 
    print(div) 

真正的問題,我從這個有一些其他的例子後,如果有什麼問題的方式,我已經寫了公式,或者如果它不可能以這種方式得到正確的答案,因爲float和小數的數字在Python中是如何工作的。希望有人能夠指出我在這裏做錯了什麼是正確的方向。

+0

你能舉出'n'和'i'的例子嗎?他們大嗎? – mitoRibo

+0

是的。以n = 9998和i = 4爲例,兩個第一個函數產生的答案有點不同,最後一個答案是正確答案。 – Siesta

回答

1

這些微小的差異似乎來自使用浮點運算。但是,如果您確定ni是整數,則在例程中根本不需要浮點值。你可以做

def binomial(n, i): 
    result = 1 
    for j in range(1, n-i+1): 
     result = result * (i+j) // j 
    return result 

這工作,因爲連續的2號的產品是由1 * 2整除,連續3數的乘積是1 * 2 * 3整除,...妮連續的產品數字可以被(ni)整除!上面的代碼中的計算順序是隻有整數結果,所以你得到一個確切的答案。這是因爲我的代碼不像計算代碼那樣計算(i+j)/j;它計算result * (i+j)然後除以j。此代碼在保持整數值儘可能小的情況下也做得相當好,這應該會提高速度。

如果當然,如果ni是浮動而不是整數,這可能無法正常工作。還要注意,這段代碼並不檢查0 <= i <= n,應該這樣做。

0

我確實將float精度視爲主要問題。你做浮點除法,這意味着你的整數可能會四捨五入。我建議你將分子和分母保持爲單獨的數字,並最終進行分割。或者,如果數字使用這種方法變得太大,那麼寫一些gcd計算並取消一些常見因素。但只能做整數除法(//)以避免精度損失。