Efficient and precise calculation of the euclidean distance

前端 未结 5 555
独厮守ぢ
独厮守ぢ 2020-12-09 11:50

Following some online research (1, 2, numpy, scipy, scikit, math), I have found several ways for calculating the Euclidean Distance in Python:



        
5条回答
  •  一向
    一向 (楼主)
    2020-12-09 12:32

    I don't know how the precision and speed compares to the other libraries you mentioned, but you can do it for 2D vectors using the built-in math.hypot() function:

    from math import hypot
    
    def pairwise(iterable):
        "s -> (s0, s1), (s1, s2), (s2, s3), ..."
        a, b = iter(iterable), iter(iterable)
        next(b, None)
        return zip(a, b)
    
    a = (52, 106, 35, 12)
    b = (33, 153, 75, 10)
    
    dist = [hypot(p2[0]-p1[0], p2[1]-p1[1]) for p1, p2 in pairwise(tuple(zip(a, b)))]
    print(dist)  # -> [131.59027319676787, 105.47511554864494, 68.94925670375281]
    

提交回复
热议问题