简体   繁体   中英

Compute euclidean distance of sequance points in python

I have two lists, X_list includes x coordinates values of n points and similarly, Y_list includes y coordinates values of the same n points.

 X_list = [x1,x2,x3, ....., xn],
 Y_list = [y1,y2,y3, ......, yn]

I want to compute the Euclidian distance between every two sequential points (eg, E_d1 = sqrt (x2-x1)**2 + (y2-y1)**2 , & E_d2 = sqrt (x3-x2)**2 + (y3-y2)**2 & so on. Finally I want to get a list that contains all n estimated E_d values.

Final_E_d = [E_d1, E_d2, E_d3,......,E_dn]

I searched and found many codes.

My code is as follows but still give me "out of index error"!!

import math
E_distance_list = []
def euclidean(v1, v2):
  for i in range(len(v1)):
    E_distance = math.sqrt(((v1[i] - v1[i+1]) ** 2) + ((v2[i] - v2[i+1]) ** 2))
    print(E_distance)
    E_distance_list.append(E_distance)
    print(E_distance_list)    
return E_distance_list

x = [211, 224, 244, 265, 295, 327, 369]
y = [1301, 1297, 1292, 1286, 1279, 1272, 1266]

print(euclidean(x,y))

Your error is probably because your index is getting out of range. Think of the last iteration. i=len(v1) -1 but you are trying to get a value from v1[i+1] . But since the last element in the list is only in the position of len(v1)-1 , then you are trying to reach an element which is not exist in the list. So i used your code and just reduced the range by 1, and the code works fine:

import math

E_distance_list = []
def euclidean(v1, v2):
    for i in range(len(v1)-1):
        E_distance = math.sqrt(((v1[i] - v1[i+1]) ** 2) + ((v2[i] - v2[i+1]) ** 2))
#        print(E_distance)
        E_distance_list.append(E_distance)
#        print(E_distance_list)    
    return E_distance_list

x = [211, 224, 244, 265, 295, 327, 369]
y = [1301, 1297, 1292, 1286, 1279, 1272, 1266]

print(euclidean(x,y))

And the output is:

[13.601470508735444, 20.615528128088304, 21.840329667841555, 30.805843601498726, 32.7566787083184, 42.42640687119285]

A nice pythonic way to calculate the euclidean distance between coordinates is to use numpy

import numpy as np

def euclidean(v1, v2):
    np_v1 = np.array(v1)
    np_v2 = np.array(v2)
    return np.linalg.norm(np_v2 - np_v1) #Order depends on which way you want to calculate the Euclidean distance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM