numpy计算路线距离
觉得有用的话,欢迎一起讨论相互学习~
标记路线上的点
[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)}
]