2014-10-16 140 views
1

我不明白爲什麼這個代碼返回False:爲什麼這個返回False

list_of_disks = [[170, 158, 470, 0.1], [135, 176, 410, 0.2], [100, 193, 350, 0.3], [170, 458, 470,  1.1]] 
def f1(pos): 
    for x in range(0, len(list_of_disks)): 
     if list_of_disks[x][3] == pos: 
      print list_of_disks[x+1][3] - 0.1, list_of_disks[x][3] 
      print list_of_disks[x+1][3] - 0.1 == list_of_disks[x][3] # Why is this False..? 
      break 

f1(0.2) 

當我打印出來的2個值,他們似乎是一樣的..? 希望有人能幫助我,謝謝!

+8

浮點不能被依賴那麼精確。 – 2014-10-16 14:39:57

+3

請參閱Python教程的[「浮點:問題和限制」](https://docs.python.org/2/tutorial/floatingpoint.html)。另請參閱[「每位計算機科學家應瞭解的浮點算術知識」](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html)。 – 2014-10-16 14:44:03

+0

我認爲精度是這裏的問題。 – 2014-10-16 14:44:19

回答

1

這是因爲0.1不能由計算機被存儲(那裏是它沒有確切的二進制表示),所以0.3-0.1是不一樣的0.2至蟒:

>>> 0.3-0.1==0.2 
False 

對MOR詳見http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/浮點精度。

您可以通過使用Decimal模塊來避免這些缺陷,該模塊是精確十進制浮點運算的一種實現。

The purpose of this module is to support arithmetic using familiar 
"schoolhouse" rules and to avoid some of the tricky representation 
issues associated with binary floating point. The package is especially 
useful for financial applications or for contexts where users have 
expectations that are at odds with binary floating point (for instance, 
in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead 
of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected 
Decimal('0.00')).