2013-02-18 161 views
0

有一個Python代碼如下:爲什麼Python在某些情況下不能判斷1.0等於1,但其他情況可以嗎?

import sys 
import fileinput, string 
K = 3 
f = raw_input("please input the initial "+str(K)+" lamba: ").split() 

Z = [] 
sumoflamba = 0.0 
for m in f: 
    j = m.find("/") 
    if j!=-1: 
      e=float(m[:j])/float(m[j+1:]) 
    else: 
      e = float(m) 
    sumoflamba+=e 
    if e==0: 
      print "the initial lamba cannot be zero!" 
      sys.exit() 
    Z.append(e) 
print sumoflamba 
if sumoflamba!=1: 
    print "initial lamba must be summed to 1!" 
    sys.exit() 

當我和0.7,0.2,0.1運行它。它會打印警告並退出!但是,當我運行0.1,0.2,0.7。它工作正常。 0.3,0.3,0.4也可以正常工作。我沒有線索......請有人解釋一下嗎? 「print sumoflamda」將爲所有這些情況提供1.0。

+2

[必須鏈接](http://docs.oracle.com/cd/E19957-01/806- 3568/ncg_goldberg.html) – 2013-02-18 01:14:28

+0

我想,Lattyware的鏈接可以解決問題。爲了更加簡潔地說明問題,可以在Python解釋器中運行'.7 + .2 + .1'。 – Blckknght 2013-02-18 01:18:14

+3

[每個計算機科學家應該知道的關於浮點算術](http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html) – 2013-02-18 01:18:51

回答

4

幾乎Lattyware提供的鏈接說明了什麼 - 但簡而言之,不能期望在不明確精度的情況下使用浮點運算來進行相等比較。如果要將值舍入或將其轉換爲整數,您將得到可預測的結果

>>> f1 = 0.7 + 0.2 + 0.1 
>>> f2 = 0.1 + 0.2 + 0.7 
>>> f1 == f2 
False 
>>> round(f1,2) == round(f2,2) 
True 
0

浮球不精確。與他們一起經營的越多,他們積累的不準確性就越高。有些數字可以完全表示,但大多數不能。比較他們的平等幾乎總是一個錯誤。

相關問題