-1

说明:以下代码接收两个 n 维点的坐标。它计算这两个点的曼哈顿距离 代码:

def manhanttan( ponto1, ponto2 ):
    totalp1 = 0
    totalp2 = 0
    for x in range( 0, len( ponto1 ) ):
        totalp1 += ponto1[x]
        totalp2 += ponto2[x]
    return abs( totalp1 - totalp2 )

def manhanttan( ponto1, ponto2 ):
    total = 0
    for x in range( 0, len( ponto1 ) ):
        total += abs( ponto1[x] - ponto2[x] )
    return total

给出不同的结果,我不知道为什么。有人可以帮助我吗?

PS:列表中的所有值都是正数

PS2:第一个我的分类得到

K1: Expected Class: 6, Found Class: 0 K2: Expected Class: 6, Found Class: 0 K3: Expected Class: 6, Found Class: 0 K4: Expected Class: 6, Found Class: 0 K5: Expected Class: 6, Found Class: 0

和另一个我得到 K1: Expected Class: 6, Found Class: 6 K2: Expected Class: 6, Found Class: 6 K3: Expected Class: 6, Found Class: 6 K4: Expected Class: 6, Found Class: 6 K5: Expected Class: 6, Found Class: 6

4

3 回答 3

3

为什么你认为它们应该是一样的?

考虑仅对单个数字序列求和:

a = [1, -1, 1, -1, 1, -1]

如果您将绝对值作为总计,那么您实际上是在对序列求和:

a = [1, 1, 1, 1, 1, 1]

这将导致总数报告为6。但是,如果你等到最后,取绝对值,你会得到a( 0) 的总和并取绝对值仍然是0

*注意——仅仅因为每个列表中的所有值都是正数并不意味着它们的差异是。eg
ponto1[x] - ponto2[x]仍然可能是负数

于 2014-10-29T16:30:46.403 回答
1

It shouldn't give the save results.

Consider p1 = [0,1] and p2 = [1,0].

Then abs(sum(p1)-sum(p2)) gives 0, where sum(abs(p1-p2)) gives 2.

The distribution property of the summation gives you that abs(sum(p1)-sum(p2)) == abs(sum(p1-p2)), so you should only take the absolute value once you have calculated the total difference.

By the way, sum is a built-in python function that does exactly what you think it does.

于 2014-10-29T17:03:09.747 回答
0

您的第二个功能是计算两个向量之间的曼哈顿距离,即每个单独维度相距多远的总和。第一个函数在取差之前将每个向量减少为一个数字;假设所有坐标都是正的,这意味着它需要从 origo 到每个向量的曼哈顿距离,然后取它们的差。这是一个非常不同的功能!

考虑这对二维向量:

y
5   a
4
3
2         b
1
0 o
  0 1 2 3 4 5 x

这里我们在 (0,0) 处有 origo,在 (1,5) 处有 a,在 (4,2) 处有 b。要从 a 到 b,我需要移动 ba=(4-1,2-5)=(3,-3),总共 sum(map(abs,[3,-3]))=6脚步。但是从 o 到 a 是 6 步,从 o 到 b 也是如此,所以归约第一方法认为 a 和 b 相等,即使它们恰好位于穿过 (6,0) 和 (0) 的同一距离线上,6) (因为相当于一个圆的曼哈顿距离实际上是一个菱形,一个 45° 旋转的正方形)。

于 2014-10-29T16:54:55.927 回答