2013-03-05 51 views
0

考慮以下幾點:這是Python 2.7.1中的一個數字比較中的錯誤嗎?

Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> x = 2.0 
>>> print x < 2.0 
False 
>>> 
>>> x = 2.2 
>>> x -= 0.2 
>>> print x < 2.0 
False 
>>> 
>>> x = 2.4 
>>> x -= 0.2 
>>> x -= 0.2 
>>> print x < 2.0 
True 
>>> print x 
2.0 

爲什麼二號的最後一條語句打印真正的從2.4到2.0,當x減少?我錯過了什麼?

+3

浮點錯誤熊。 (請參閱[這裏](http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken)瞭解JavaScript的等價物)。 – 2013-03-05 07:37:15

+5

[浮點運算可能不準確](http://docs.python.org/2/tutorial/floatingpoint.html) – Volatility 2013-03-05 07:37:24

回答

7

你缺少這樣的事實,無論是2.4還是0.2都確切float表示:

In [31]: '%.20f' % 2.4 
Out[31]: '2.39999999999999991118' 

In [32]: '%.20f' % 0.2 
Out[32]: '0.20000000000000001110' 

這樣:

In [33]: '%.20f' % (2.4 - 0.2 - 0.2) 
Out[33]: '1.99999999999999977796' 

小於2.0。

這將在tutorial中進一步討論(儘管值得注意的是該問題決不是Python特有的,但是是浮點數的一般限制)。

3

如評論所述,與定點數相比,浮點數通常具有不準確性。你可以問到Python得到的這多一點提示更精確打印數量:

>>> '%0.20g' % (2.4 - 0.2 - 0.2) 
'1.999999999999999778' 

正如你所看到的,這個數小於2

如果你想使用具有固定精度的數字數據類型,Python提供了Decimal數據類型。

>>> from decimal import Decimal 
>>> Decimal('2.4') - Decimal('0.2') - Decimal('0.2') 
Decimal('2.0') 
>>> Decimal('2.0') < 2.0 
False 

但是記住,十進制運算會比建在浮點運算速度較慢,因此需要額外的精度時,才應使用(例如,在財務計算)

+1

浮點數* *可以是「你想要的數字」:1,2, 4,0.5,...都是確切的。 – EOL 2013-03-05 07:51:50

+0

我編輯了答案,指出浮點與定點相比具有不準確性。 – 2013-03-05 07:57:15