gpt4 book ai didi

python - 为什么这会返回 False

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:30 24 4
gpt4 key购买 nike

我不明白为什么这段代码返回 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

参见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')).

关于python - 为什么这会返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26407143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com