Reputation: 1439
I'd like to check if two points are identical within an absolute tolerance value in the most 'pythonic' and simple way.
I am currently using 'numpy' built-in function allclose()
:
numpy.allclose(a, b, 0, tol)
But I am looking for a 'non-numpy' solution if possible.
Example
a = [1, 2, 3]
b = [1.1, 2.1, 3.1]
c = [1, 3, 3]
tolerance = 0.5
a
compared to b
should return true
a
compared to c
should return false
Upvotes: 0
Views: 613
Reputation: 6012
For two dimensions you can use:
>>> 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
>>>
And for more:
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
Update per Rockcat's comment (more efficient):
same = lambda p1, p2, tol: sum((p2[i] - p1[i])**2 for i in range(len(p1))) <= tol**2
A prettier version (maybe faster):
from operator import sub
same = lambda p1, p2, tol: sum(x**2 for x in map(sub, p1, p2)) <= tol**2
Upvotes: 2