为什么这会返回False

时间:2014-10-16 14:38:56

标签: 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_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个值时,它们似乎是相同的......? 希望有人可以帮助我,谢谢!

1 个答案:

答案 0 :(得分:1)

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

>>> 0.3-0.1==0.2
False

有关浮点精度的详细信息,请参阅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')).