numpy 计算路线距离

时间:2022-07-23
本文章向大家介绍numpy 计算路线距离,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

“参考文献enumerate 遍历数组[1]np.diff 函数[2]numpy 适用数组作为索引[3]

标记路线上的点

X={X1,X2,X3,X4,X5,X6}
Xn=(x_n,y_n)
import numpy as np
# 适用二维数组表示地图上的六个点
# city_position.shape=(6,2) 表示旅行商经过的路线
city_position=np.array([[1,18],[6,23],[8,64],[7,49],[49,48],[12,36]])

存储路线上的点

point_x=np.ones((6,1))
point_y=np.ones((6,1))
point_x=city_position[:,0] # 存放路线的横坐标
point_y=city_position[:,1] # 存放路线的纵坐标
# print(point_x)
# print(point_y)
# [ 1  6  8  7 49 12]
# [18 23 64 49 48 36]

依次计算路线上点之间的距离

total_distance=sum_{n=2}^{n}sqrt{(x_n-x_{n-1})^2+(y_n-y_{n-1})^2}
# 计算路线的距离
total_distance=np.sum(np.sqrt(np.square(np.diff(point_x)) + np.square(np.diff(point_y))))
print("total_distance",total_distance)
print("np.diff(point_x)",np.diff(point_x))
print("np.diff(point_y)",np.diff(point_y))
# total_distance 144.062319447
# np.diff(point_x) [  5   2  -1  42 -37]
# np.diff(point_y) [  5  41 -15  -1 -12]
sqrt{(5^2+5^2)}+sqrt{(2^2+41^2)}+sqrt{((-1)^2+(-15)^2)}+sqrt{(42^2+(-1)^2)}+sqrt{((-37)^2+(-12)^2)}

参考资料

[1]enumerate遍历数组: https://blog.csdn.net/u013555719/article/details/83578489

[2]np.diff函数: https://blog.csdn.net/u013555719/article/details/83586177

[3]numpy适用数组作为索引: https://blog.csdn.net/u013555719/article/details/83582679