我試圖寫一個函數來計算使用這個公式二項式係數計算二項式係數時:回答錯誤使用改良式
我遇到的問題是,我不能疥癬,以得到正確的答案。這是我試圖編寫函數的兩種方法的一個例子。
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中是如何工作的。希望有人能夠指出我在這裏做錯了什麼是正確的方向。
你能舉出'n'和'i'的例子嗎?他們大嗎? – mitoRibo
是的。以n = 9998和i = 4爲例,兩個第一個函數產生的答案有點不同,最後一個答案是正確答案。 – Siesta