使用列表运算符"in"具有浮点值 [英] using list operator "in" with floating point values
问题描述
我有一个带有浮点数的列表,每个数字都有3个小数(例如474.259).如果我这样验证清单中的号码:
I have a list with floats, each number with 3 decimals (eg. 474.259). If I verify the number in the list like this:
if 474.259 in list_sample:
print "something!"
然后显示该消息,但是如果我从另一个列表中取出该数字并四舍五入,则将其舍入:
Then the message is shown, but if I take the number from another list and I round it:
number = other_list[10]
number = round(number, 3)
if number == 474.259:
print "the numbers are same!"
if number in list_sample:
print "something!"
第二条消息未显示.
推荐答案
比较浮点数是否完全相等通常无法满足您的要求.这是因为计算机中的浮点数具有一种表示形式(存储格式),这种表示形式对于许多实数本质上是不准确的.
Comparing floating point numbers for exact equality usually won't do what you want. This is because floating point numbers in computers have a representation (storage format) which is inherently inaccurate for many real numbers.
我建议在这里阅读: http://floating-point-gui.de/并使用ε"容差值进行模糊比较"之类的事情,以使数字相等,只要它们之间的差异小于x%或其他即可.
I suggest reading about it here: http://floating-point-gui.de/ and doing something like a "fuzzy compare" using an "epsilon" tolerance value to consider the numbers equal so long as they differ by less than x% or whatever.
这篇关于使用列表运算符"in"具有浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!