python計(jì)算兩點(diǎn)間距離的5種常用方法
計(jì)算兩點(diǎn)距離在 Python 中有多種方法,我為你介紹幾種最常用的方式:
方法一:使用歐幾里得距離公式(最基礎(chǔ))
這是最直接的方法,使用數(shù)學(xué)公式:距離 = √[(x? - x?)² + (y? - y?)²]
import math
def distance_between_points(p1, p2):
"""計(jì)算兩點(diǎn)之間的歐幾里得距離"""
x1, y1 = p1
x2, y2 = p2
# 計(jì)算距離
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"兩點(diǎn) {point1} 和 {point2} 之間的距離是: {dist}")
# 輸出: 5.0
方法二:使用math.dist()(Python 3.8+ 推薦)
Python 3.8 及以上版本提供了內(nèi)置函數(shù) math.dist(),這是最簡(jiǎn)潔的方法:
import math
point1 = (1, 2)
point2 = (4, 6)
# 直接計(jì)算
distance = math.dist(point1, point2)
print(f"距離: {distance}")
# 輸出: 5.0
優(yōu)點(diǎn):
- 代碼最簡(jiǎn)潔
- 支持任意維度的點(diǎn)(2D、3D等)
- 性能優(yōu)化過(guò)
方法三:使用 NumPy(適合大量計(jì)算)
如果你需要處理大量數(shù)據(jù)或進(jìn)行科學(xué)計(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: 手動(dòng)計(jì)算
distance = np.sqrt(np.sum((point2 - point1)**2))
print(f"距離: {distance}")
# 輸出: 5.0
# 方法 3.3: 批量計(jì)算多個(gè)點(diǎn)
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"多個(gè)距離: {distances}")
# 輸出: [5. 5.65685425 5.65685425]
方法四:使用 SciPy(功能最強(qiáng)大)
SciPy 提供了更多距離計(jì)算選項(xiàng)(曼哈頓距離、切比雪夫距離等):
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}")
方法五:不開(kāi)方的距離(用于比較)
如果你只是需要比較距離大小,不需要實(shí)際距離值,可以省略開(kāi)方操作以提高性能:
def distance_squared(p1, p2):
"""計(jì)算距離的平方(不開(kāi)方)"""
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
# 比較時(shí)不需要開(kāi)方
if dist2_1 < dist2_2:
print("point2 更近")
elif dist2_1 > dist2_2:
print("point3 更近")
else:
print("距離相等")
完整示例:包含 3D 點(diǎn)
import math
def calculate_distance(p1, p2):
"""支持任意維度的點(diǎn)"""
if len(p1) != len(p2):
raise ValueError("兩點(diǎn)維度必須相同")
# 計(jì)算各維度差值的平方和
sum_of_squares = sum((a - b)**2 for a, b in zip(p1, p2))
# 開(kāi)方
return math.sqrt(sum_of_squares)
# 2D 點(diǎn)
p1_2d = (1, 2)
p2_2d = (4, 6)
print(f"2D 距離: {calculate_distance(p1_2d, p2_2d)}")
# 3D 點(diǎn)
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)}")
性能對(duì)比建議
| 場(chǎng)景 | 推薦方法 |
|---|---|
| 簡(jiǎn)單的 2D/3D 距離計(jì)算 | math.dist() (Python 3.8+) |
| 需要兼容舊版本 Python | 手動(dòng)公式 + math.sqrt() |
| 批量計(jì)算大量點(diǎn) | NumPy 的 np.linalg.norm() |
| 需要多種距離度量 | SciPy 的 scipy.spatial.distance |
| 只需比較距離大小 | 距離平方(不開(kāi)方) |
最推薦:如果你使用 Python 3.8+,直接用 math.dist(),代碼最簡(jiǎn)潔且性能好!
到此這篇關(guān)于python計(jì)算兩點(diǎn)間距離的5種常用方法的文章就介紹到這了,更多相關(guān)python計(jì)算兩點(diǎn)間距離內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pandas如何實(shí)現(xiàn)兩個(gè)dataframe相減
這篇文章主要介紹了pandas如何實(shí)現(xiàn)兩個(gè)dataframe相減方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
Python argparse模塊應(yīng)用實(shí)例解析
這篇文章主要介紹了Python argparse模塊應(yīng)用實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
Django Form 實(shí)時(shí)從數(shù)據(jù)庫(kù)中獲取數(shù)據(jù)的操作方法
這篇文章主要介紹了Django Form 實(shí)時(shí)從數(shù)據(jù)庫(kù)中獲取數(shù)據(jù)的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2019-07-07
pytorch/transformers?最后一層不加激活函數(shù)的原因分析
這里給大家解釋一下為什么bert模型最后都不加激活函數(shù),是因?yàn)閾p失函數(shù)選擇的原因,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2023-01-01
python實(shí)現(xiàn)添加圖片到word文檔中
這篇文章主要介紹了python實(shí)現(xiàn)添加圖片到word文檔中方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
使用Python給PDF添加目錄書(shū)簽的實(shí)現(xiàn)方法
有時(shí)下載到掃描版的 PDF 是不帶書(shū)簽?zāi)夸浀?這樣閱讀起來(lái)很不方便,下面通過(guò) python 實(shí)現(xiàn)一個(gè)半自動(dòng)化添加書(shū)簽?zāi)夸浀哪_本,文中通過(guò)代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2023-10-10

