numpy計算路線距離

2022-03-19 08:34:52 字數 1203 閱讀 7032

參考文獻

enumerate遍歷陣列

np.diff函式

numpy適用陣列作為索引

\[x=

\]\[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_^\sqrt)^2+(y_n-y_)^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+\sqrt+\sqrt+\sqrt+\sqrt

\]

Numpy中計算各種距離

詳細 1.閔可夫斯基距離 minkowski distance 2.歐氏距離 euclidean distance 3.曼哈頓距離 manhattan distance 4.切比雪夫距離 chebyshev distance 5.夾角余弦 cosine 6.漢明距離 hamming distance...

python 計算向量歐氏距離 numpy

給定兩個向量,計算歐式距離 直接呼叫numpy中的幾個函式就行了 這種東西,絕對不要自己寫,哈哈 涉及到怎麼將list轉化為numpy的array python view plain copy defcaleuclideandistance vec1,vec2 dist numpy.sqrt num...

用numpy高效計算歐氏距離

在各類演算法中,距離的計算極其常見,用numpy來計算效率非常的高,其計算方式也有很多。個人認為最直觀也非常高效的一種方式如下 首先看二維歐式距離的公式定義d 那麼就依據公式的定義,我們直觀的來設定計算公式,廢話不多說直接見 import numpy as np a np.arange 16 res...