当前位置: 代码网 > it编程>前端脚本>Python > python计算两点间距离的5种常用方法

python计算两点间距离的5种常用方法

2026年04月16日 Python 我要评论
计算两点距离在 python 中有多种方法,我为你介绍几种最常用的方式:方法一:使用欧几里得距离公式(最基础)这是最直接的方法,使用数学公式:距离 = √[(x₂ - x₁)²

计算两点距离在 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计算两点间距离内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com