我想检查两个点在绝对容差值内是否相同,以最“pythonic”和简单的方式。
我目前正在使用'numpy'内置函数allclose()
:
numpy.allclose(a, b, 0, tol)
但如果可能的话,我正在寻找一种“非n”的解决方案。
示例
a = [1, 2, 3]
b = [1.1, 2.1, 3.1]
c = [1, 3, 3]
tolerance = 0.5
与a
相比, b
应返回true
a
相比, c
应返回false
答案 0 :(得分:2)
您可以使用以下两个维度:
>>> import math
>>> same = lambda p1, p2, tol: math.hypot(p2[0] - p1[0], p2[1] - p1[1]) <= tol
>>> a = [1, 2]
>>> b = [1.1, 2.1]
>>> c = [1, 3]
>>> same(a, b, 0.5)
True
>>> same(b, c, 0.5)
False
>>>
还有更多:
multiHypot = lambda diffs: math.sqrt(sum(diff**2 for diff in diffs))
same = lambda p1, p2, tol: multiHypot(p2[i] - p1[i] for i in range(len(p1))) <= tol
根据Rockcat的评论更新(效率更高):
same = lambda p1, p2, tol: sum((p2[i] - p1[i])**2 for i in range(len(p1))) <= tol**2
更漂亮的版本(可能更快):
from operator import sub
same = lambda p1, p2, tol: sum(x**2 for x in map(sub, p1, p2)) <= tol**2