[英]Calculating Euclidean Distance in Python
I am trying to calculate Euclidean distance in python using the following steps outlined as comments.我正在尝试使用以下作为注释概述的步骤来计算 python 中的欧几里得距离。 It keeps on saying my calculation is wrong.
它一直说我的计算是错误的。 I'm not sure why.
我不确定为什么。
def euclidean_distance(vector1 , vector2):
## the sum_squares variable will contain the current value of the sum of squares of each i-th coordinate pair
sum_squares = 0
numberOfIterations = len(vector1)
## TODO: Complete loop below ##
# The number of times the loop will be executed is the length of the vectors.
#
# At each loop iteration, you will:
# Step 1. index into each vector and find the difference between
#the ith element in vector2 and vector1
# Step 2. square the difference
# Step 3. update the value of the 'sum_squares' variable by
#adding the result in Step 2 to
# the existing value of sum_squares
for i in range(numberOfIterations):
# Inside this loop follow steps 1-3 to update the value of THE
#'sum_squares' variable by adding the squared difference of the i'th coordinate pair to the sum.
dist = ((vector2[0] - vector1[i]) **2 + (vector1[0] - vector2[i]) **2)
sum_squares = sum_squares + dist
### TODO: Compute the Distance ###
# Compute the square root of the variable 'sum_squares' and assign
# that result to a new variable named 'distance'
import math
distance = math.sqrt(sum_squares)
# return the Euclidean distance
return distance
The problem is just with your code of calculating the distance.问题仅在于您计算距离的代码。
# Step 1. index into each vector and find the difference between
#the ith element in vector2 and vector1
# Step 2. square the difference
Using these two steps, the correct line of code should be:使用这两个步骤,正确的代码行应该是:
dist = (vector2[i] - vector1[i]) ** 2
This will square the distance between the i'th coordinate pair, and the next line will add it to the variable sum_squares
这将对第 i 个坐标对之间的距离进行平方,下一行会将其添加到变量
sum_squares
We can see that changing this line of code will give us the correct answer:我们可以看到,改变这行代码会给我们正确的答案:
print(euclidean_distance([1,2],[2,3])) #1.414
print(euclidean_distance([1,2,3],[4,8,10])) #9.695
as:作为:
sqrt( (2 - 1)^2 + (3 - 2)^2 ) = sqrt(2) = 1.414
sqrt( (4 - 1)^2 + (8 - 2)^2 + (10 - 3)^2 ) = sqrt(94) = 9.695
I hope this helped!我希望这有帮助! Let me know if you need any further help or clarification :)
如果您需要任何进一步的帮助或澄清,请告诉我:)
Iteration over the lists (vectors) is best achieved with zip() .最好使用zip()实现对列表(向量)的迭代。 Summation of the squares is best achieved with sum() .
平方和最好用sum()来实现。 Therefore:
所以:
def euclidean_distance(vx, vy):
return sum((y-x)**2 for x, y in zip(vx, vy)) ** 0.5
print(euclidean_distance([1,2,3,4],[4,8,10,12]))
Output:输出:
12.569805089976535
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.