import math
from math import sqrt
Hailey=[0,4,1,4,0,0,4,1]
Verica=[3,0,0,5,4,2.5,3,0]
temp=[]
distance=0
x=0
for i in range(0,len(Hailey)):
if (Hailey[i]!=0 and Verica[i]!=0):
temp[x]=math.sqrt(abs(Hailey[i]**2) - abs(Verica[i]**2))
x=x+1
for i in range(0,len(temp)):
distance=distance+temp[i]
print("distance is",distance)
我试图制作一个程序,找出2个人之间的欧氏距离。它似乎在数学上是正确的,我得到了这个:
distance=distance + math.sqrt(abs(Hailey[i]**2) - abs(Verica[i]**2))
ValueError: math domain error
答案 0 :(得分:6)
您使用的公式并不完全正确。这是correct formula:
>>> math.sqrt(sum((h-v)**2 for h, v in zip(Hailey, Verica)))
7.158910531638177
或者,如果您想使用NumPy:
>>> Hailey = numpy.array([0,4,1,4,0,0,4,1])
>>> Verica = numpy.array([3,0,0,5,4,2.5,3,0])
>>> numpy.linalg.norm(Hailey - Verica)
7.1589105316381767