2013-03-05 57 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