# Python 中計算歐幾里得距離

Manav Narula 2023年1月30日

## 使用 NumPy 模組查詢兩點之間的歐幾里得距離

``````import numpy as np

a = np.array((1, 2, 3))
b = np.array((4, 5, 6))

dist = np.linalg.norm(a - b)

print(dist)
``````

``````5.196152422706632
``````

``````import numpy as np

a = np.array((1, 2, 3))
b = np.array((4, 5, 6))

dist = np.sqrt(np.sum(np.square(a - b)))

print(dist)
``````

``````5.196152422706632
``````

`numpy.sqrt()` 函式提供值的平方根。

``````import numpy as np

a = np.array((1, 2, 3))
b = np.array((4, 5, 6))

temp = a - b
dist = np.sqrt(np.dot(temp.T, temp))

print(dist)
``````

``````5.196152422706632
``````

## 使用 `distance.euclidean()` 函式查詢兩點之間的歐式距離

scipy 庫具有許多用於數學和科學計算的功能。`distance.euclidean()` 函式返回兩點之間的歐幾里得距離。

``````from scipy.spatial import distance

a = (1, 2, 3)
b = (4, 5, 6)

print(distance.euclidean(a, b))
``````

``````5.196152422706632
``````

## 使用 `math.dist()` 函式查詢兩點之間的歐幾里得距離

`math` 模組也可以用作替代。該模組的 `dist()` 函式可以返回兩點之間的線段。

``````from math import dist

a = (1, 2, 3)
b = (4, 5, 6)

print(dist(a, b))
``````

``````5.196152422706632
``````

`scipy``math` 模組方法是 `NumPy` 方法的更快替代方法，當座標為元組或列表形式時可以使用。

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.