python計算兩點間距離的5種常用方法
計算兩點距離在 Python 中有多種方法,我為你介紹幾種最常用的方式:
方法一:使用歐幾里得距離公式(最基礎)
這是最直接的方法,使用數(shù)學公式:距離 = √[(x? - x?)² + (y? - y?)²]
import math
def distance_between_points(p1, p2):
"""計算兩點之間的歐幾里得距離"""
x1, y1 = p1
x2, y2 = p2
# 計算距離
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
return distance
# 示例
point1 = (1, 2)
point2 = (4, 6)
dist = distance_between_points(point1, point2)
print(f"兩點 {point1} 和 {point2} 之間的距離是: {dist}")
# 輸出: 5.0
方法二:使用math.dist()(Python 3.8+ 推薦)
Python 3.8 及以上版本提供了內(nèi)置函數(shù) math.dist(),這是最簡潔的方法:
import math
point1 = (1, 2)
point2 = (4, 6)
# 直接計算
distance = math.dist(point1, point2)
print(f"距離: {distance}")
# 輸出: 5.0
優(yōu)點:
- 代碼最簡潔
- 支持任意維度的點(2D、3D等)
- 性能優(yōu)化過
方法三:使用 NumPy(適合大量計算)
如果你需要處理大量數(shù)據(jù)或進行科學計算,NumPy 是最佳選擇:
import numpy as np
# 方法 3.1: 使用 np.linalg.norm
point1 = np.array([1, 2])
point2 = np.array([4, 6])
distance = np.linalg.norm(point2 - point1)
print(f"距離: {distance}")
# 輸出: 5.0
# 方法 3.2: 手動計算
distance = np.sqrt(np.sum((point2 - point1)**2))
print(f"距離: {distance}")
# 輸出: 5.0
# 方法 3.3: 批量計算多個點
points1 = np.array([[1, 2], [3, 4], [5, 6]])
points2 = np.array([[4, 6], [7, 8], [9, 10]])
distances = np.linalg.norm(points2 - points1, axis=1)
print(f"多個距離: {distances}")
# 輸出: [5. 5.65685425 5.65685425]
方法四:使用 SciPy(功能最強大)
SciPy 提供了更多距離計算選項(曼哈頓距離、切比雪夫距離等):
from scipy.spatial import distance
point1 = (1, 2)
point2 = (4, 6)
# 歐幾里得距離
euclidean_dist = distance.euclidean(point1, point2)
print(f"歐幾里得距離: {euclidean_dist}")
# 曼哈頓距離 (|x2-x1| + |y2-y1|)
manhattan_dist = distance.cityblock(point1, point2)
print(f"曼哈頓距離: {manhattan_dist}")
# 切比雪夫距離 (max(|x2-x1|, |y2-y1|))
chebyshev_dist = distance.chebyshev(point1, point2)
print(f"切比雪夫距離: {chebyshev_dist}")
方法五:不開方的距離(用于比較)
如果你只是需要比較距離大小,不需要實際距離值,可以省略開方操作以提高性能:
def distance_squared(p1, p2):
"""計算距離的平方(不開方)"""
x1, y1 = p1
x2, y2 = p2
return (x2 - x1)**2 + (y2 - y1)**2
point1 = (1, 2)
point2 = (4, 6)
point3 = (5, 5)
dist2_1 = distance_squared(point1, point2) # 25
dist2_2 = distance_squared(point1, point3) # 25
# 比較時不需要開方
if dist2_1 < dist2_2:
print("point2 更近")
elif dist2_1 > dist2_2:
print("point3 更近")
else:
print("距離相等")
完整示例:包含 3D 點
import math
def calculate_distance(p1, p2):
"""支持任意維度的點"""
if len(p1) != len(p2):
raise ValueError("兩點維度必須相同")
# 計算各維度差值的平方和
sum_of_squares = sum((a - b)**2 for a, b in zip(p1, p2))
# 開方
return math.sqrt(sum_of_squares)
# 2D 點
p1_2d = (1, 2)
p2_2d = (4, 6)
print(f"2D 距離: {calculate_distance(p1_2d, p2_2d)}")
# 3D 點
p1_3d = (1, 2, 3)
p2_3d = (4, 6, 8)
print(f"3D 距離: {calculate_distance(p1_3d, p2_3d)}")
# 使用 math.dist (Python 3.8+)
print(f"3D 距離 (math.dist): {math.dist(p1_3d, p2_3d)}")
性能對比建議
| 場景 | 推薦方法 |
|---|---|
| 簡單的 2D/3D 距離計算 | math.dist() (Python 3.8+) |
| 需要兼容舊版本 Python | 手動公式 + math.sqrt() |
| 批量計算大量點 | NumPy 的 np.linalg.norm() |
| 需要多種距離度量 | SciPy 的 scipy.spatial.distance |
| 只需比較距離大小 | 距離平方(不開方) |
最推薦:如果你使用 Python 3.8+,直接用 math.dist(),代碼最簡潔且性能好!
到此這篇關于python計算兩點間距離的5種常用方法的文章就介紹到這了,更多相關python計算兩點間距離內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Django Form 實時從數(shù)據(jù)庫中獲取數(shù)據(jù)的操作方法
這篇文章主要介紹了Django Form 實時從數(shù)據(jù)庫中獲取數(shù)據(jù)的相關知識,本文給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-07-07
pytorch/transformers?最后一層不加激活函數(shù)的原因分析
這里給大家解釋一下為什么bert模型最后都不加激活函數(shù),是因為損失函數(shù)選擇的原因,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-01-01

