【问题标题】:Give tolerance comparing floats in list [duplicate]给出公差比较列表中的浮点数[重复]
【发布时间】:2020-08-02 01:52:07
【问题描述】:

我知道在比较浮点数时要给予一定的容忍度。 我可以使用,

math.isclose(0.0005, 0.0006, abs_tol = 0.0002)

它会给出 True 作为响应。

但是假设我们有两个列表

number_list_1 = [1.15679, 0.000435343, 0.009432, 10.0, 0.5678]
number_list_2 = [1.157, 0.00044, 0.0094, 10.0, 0.568]

如您所见,两个列表的元素具有几乎相同的值,但修改略有不同。

如果我比较两个列表,如何返回 True 值?

【问题讨论】:

  • 使用 for 循环遍历所有元素并使用 math.isclose(l1[i], l2[i], abs)?
  • 另外,大多数math 函数都有一个numpy 等效项。如果您愿意使用该软件包,使用 numpy.isclose 会得到您想要的。

标签: python math


【解决方案1】:

作为一个单行,你可以zip()这两个列表,然后使用all()

import math
number_list_1 = [1.15679, 0.000435343, 0.009432, 10.0, 0.5678]
number_list_2 = [1.157, 0.00044, 0.0094, 10.0, 0.568]
print(all((math.isclose(n1, n2, abs_tol = 0.0002) for n1, n2 in zip(number_list_1, number_list_2))))

或者,如果您想要更明确的内容:

def is_close(n1, n2, abs_tol=0.0002):
    if len(n1) != len(n2):
        return False    
    for n1, n2 in zip(n1, n2):
        if not math.isclose(n1, n2, abs_tol=abs_tol):
            return False            
    return True
print(is_close(number_list_1, number_list_2))

【讨论】:

  • 理解作为生成器表达式比临时列表更好
  • @MadPhysicist 很好,更新了我的答案
【解决方案2】:
import math

number_list_1 = [1.15679, 0.000435343, 0.009432, 10.0, 0.5678]
number_list_2 = [1.157, 0.00044, 0.0094, 10.0, 0.568]

for x in range(len(number_list_1)):
    for y in range(len(number_list_2)):
        print (number_list_1[x],number_list_2[y], math.isclose(x, y, abs_tol = 0.0002))

【讨论】:

    猜你喜欢
    • 2016-01-24
    • 2011-10-24
    • 2011-08-20
    • 1970-01-01
    • 2015-09-06
    • 2023-04-05
    • 2020-06-13
    相关资源
    最近更新 更多