0

考虑以下:

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

当 x 从 2.4 减少到 2.0 时,为什么最后第二条语句打印 True ?我错过了什么?

4

2 回答 2

7

You are missing the fact that neither 2.4 nor 0.2 have exact float representations:

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

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

Thus:

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

which is less than 2.0.

This is discussed further in the tutorial (although it is worth noting that the issue is in no way Python-specific, but is a general limitation of floating-point numbers).

于 2013-03-05T07:43:12.403 回答
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

但请记住,十进制运算将比内置浮点运算慢,因此仅应在需要额外精度时使用(例如,在金融计算中)

于 2013-03-05T07:49:37.130 回答