曼哈顿2向量之间的距离

时间:2020-06-29 08:26:20

标签: python distance heuristics

我需要计算两个向量之间的曼哈顿距离

我找到了此代码 https://www.geeksforgeeks.org/sum-manhattan-distances-pairs-points/

def distancesum (x, y, n): 
    sum = 0
      
    # for each point, finding distance 
    # to rest of the point 
    for i in range(n): 
        for j in range(i+1,n): 
            sum += (abs(x[i] - x[j]) +
                        abs(y[i] - y[j])) 
      
    return sum

但是在另一个文档中,我找到了曼哈顿的这段代码 enter image description here

因此,此代码为:

def manhattan_distance(instance1, instance2):
    n = len(instance1)-1
    sum = 0
    # for each point, finding distance
    # to rest of the point
    for i in range(n):
        sum += abs(float(instance1[i]) - float(instance2[i]))
    return sum

曼哈顿距离的算法是什么

2 个答案:

答案 0 :(得分:0)

在引用的公式中,您有n个点,每个点都有2个坐标,并且您要计算一个向量与另一个向量的距离。因此,除符号外,两个公式都相同。两个向量之间的曼哈顿距离是它们的坐标之差的绝对值之和。记住它的一种简单方法是,向量与自身的距离必须为0。

答案 1 :(得分:0)

这是计算曼哈顿距离的示例。

In [1]: %paste                                                                                                                                               
import numpy as np

def manhattan_distance(a, b):
    return np.abs(a - b).sum()

a = np.array([1, 2])
b = np.array([-1, 4])
print(manhattan_distance(a, b))

## -- End pasted text --
4

如果处理的是字符串矢量

In [1]: %paste                                                                                                                                               
import numpy as np

def manhattan_distance(a, b):
    return np.abs(a - b).sum()

a = ['1', '2']
b = ['-1', '4']
print(manhattan_distance(np.array(a, dtype=float), np.array(b, dtype=float)))
## -- End pasted text --
4.0
相关问题