Python 为什么返回错误

Python 为什么返回错误,python,python-2.7,Python,Python 2.7,我不明白为什么这个代码返回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_o

我不明白为什么这个代码返回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)
当我打印出这两个值时,它们似乎是相同的。。?
希望有人能帮我,谢谢

这是因为计算机无法存储0.1(没有精确的二进制表示),因此0.3-0.1与python的0.2不同:

>>> 0.3-0.1==0.2
False
有关浮点精度的详细信息,请参阅

您可以通过使用
Decimal
模块来避免这些陷阱,这是一种精确的十进制浮点算法的实现


浮点不能依赖于如此精确。请参阅Python教程的。另见。我认为精确性是关键。
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')).