組合數計算出現浮點誤差的問題python

#首先組合數公式C(n,m)可以簡單化簡,例如C(8,5)=C(8,3)=(8*7*6)/(3*2*1),m或n-m爲幾,分式上下就有幾
#個數。

def cni(n,i):#原函數
    minNI = min (i,n-i)#C(8,5)->C(8,3),減少下面循環次數
    result  = 1
    for j in range(0,minNI):
        print('(',result,'*',n -j,')/', minNI-j) #調試
        result =result*(n-j)/(minNI-j) #從最大項開始累乘
    return result

def cni1(n,i):#改正後
    minNI=min(i,n-i)
    result = 1
    for j in range(1, minNI+1):
        print('(',result,'*',n -minNI+j,')/', j)#從最小項開始累乘
        result = (result * (n -minNI+j)) /j#爲了保證能夠整除,先進行乘法後除
    return result


print('原函數:')
print(cni(8,5),end='\n\n')
print('修改後:')
print(cni1(8,5))

output-----------------------------------------
原函數:
( 1 * 8 )/ 3
( 2.6666666666666665 * 7 )/ 2
( 9.333333333333332 * 6 )/ 1
55.99999999999999

修改後:
( 1 * 6 )/ 1
( 6.0 * 7 )/ 2
( 21.0 * 8 )/ 3
56.0


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章