![](/img/trans.png)
[英]How to implement in Python a function to compute the Euclidean distance between two arbitrary points on a torus
[英]Compute euclidean distance of sequance points in python
我有兩個列表,X_list包含n點的x坐標值,類似地,Y_list包含相同n點的y坐標值。
X_list = [x1,x2,x3, ....., xn],
Y_list = [y1,y2,y3, ......, yn]
我想計算每兩個連續點之間的歐幾里得距離(例如E_d1 = sqrt (x2-x1)**2 + (y2-y1)**2
,& E_d2 = sqrt (x3-x2)**2 + (y3-y2)**2
等,最后,我想得到一個包含所有n個估計的E_d值的列表。
Final_E_d = [E_d1, E_d2, E_d3,......,E_dn]
我搜索並找到許多代碼。
我的代碼如下,但仍然給我“超出索引錯誤”!
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))
您的錯誤可能是因為您的索引超出范圍。 考慮最后一次迭代。 i=len(v1) -1
但您嘗試從v1[i+1]
獲取值。 但是,由於列表中的最后一個元素僅位於len(v1)-1
的位置,因此您試圖到達列表中不存在的元素。 所以我用了你的代碼,只是將范圍減小了1,代碼工作正常:
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))
輸出為:
[13.601470508735444, 20.615528128088304, 21.840329667841555, 30.805843601498726, 32.7566787083184, 42.42640687119285]
計算坐標之間的歐式距離的一種很好的pythonic方法是使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.