python计算两点间距离的5种常用方法
作者:detayun
计算两点距离在 Python 中有多种方法,本文介绍了在Python中计算两点距离的5种常用方法,每种方法都有各自的适用场景和优缺点,感兴趣的小伙伴可以了解下
计算两点距离在 Python 中有多种方法,我为你介绍几种最常用的方式:
方法一:使用欧几里得距离公式(最基础)
这是最直接的方法,使用数学公式:距离 = √[(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 及以上版本提供了内置函数 math.dist(),这是最简洁的方法:
import math
point1 = (1, 2)
point2 = (4, 6)
# 直接计算
distance = math.dist(point1, point2)
print(f"距离: {distance}")
# 输出: 5.0
优点:
- 代码最简洁
- 支持任意维度的点(2D、3D等)
- 性能优化过
方法三:使用 NumPy(适合大量计算)
如果你需要处理大量数据或进行科学计算,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计算两点间距离内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
