python计算两点间的距离

张开发
2026/4/15 22:36:40 15 分钟阅读

分享文章

python计算两点间的距离
计算两点距离在 Python 中有多种方法我为你介绍几种最常用的方式方法一使用欧几里得距离公式最基础这是最直接的方法使用数学公式距离 √[(x₂ - x₁)² (y₂ - y₁)²]importmathdefdistance_between_points(p1,p2):计算两点之间的欧几里得距离x1,y1p1 x2,y2p2# 计算距离distancemath.sqrt((x2-x1)**2(y2-y1)**2)returndistance# 示例point1(1,2)point2(4,6)distdistance_between_points(point1,point2)print(f两点{point1}和{point2}之间的距离是:{dist})# 输出: 5.0方法二使用math.dist()Python 3.8 推荐Python 3.8 及以上版本提供了内置函数math.dist()这是最简洁的方法importmath point1(1,2)point2(4,6)# 直接计算distancemath.dist(point1,point2)print(f距离:{distance})# 输出: 5.0优点代码最简洁支持任意维度的点2D、3D等性能优化过方法三使用 NumPy适合大量计算如果你需要处理大量数据或进行科学计算NumPy 是最佳选择importnumpyasnp# 方法 3.1: 使用 np.linalg.normpoint1np.array([1,2])point2np.array([4,6])distancenp.linalg.norm(point2-point1)print(f距离:{distance})# 输出: 5.0# 方法 3.2: 手动计算distancenp.sqrt(np.sum((point2-point1)**2))print(f距离:{distance})# 输出: 5.0# 方法 3.3: 批量计算多个点points1np.array([[1,2],[3,4],[5,6]])points2np.array([[4,6],[7,8],[9,10]])distancesnp.linalg.norm(points2-points1,axis1)print(f多个距离:{distances})# 输出: [5. 5.65685425 5.65685425]方法四使用 SciPy功能最强大SciPy 提供了更多距离计算选项曼哈顿距离、切比雪夫距离等fromscipy.spatialimportdistance point1(1,2)point2(4,6)# 欧几里得距离euclidean_distdistance.euclidean(point1,point2)print(f欧几里得距离:{euclidean_dist})# 曼哈顿距离 (|x2-x1| |y2-y1|)manhattan_distdistance.cityblock(point1,point2)print(f曼哈顿距离:{manhattan_dist})# 切比雪夫距离 (max(|x2-x1|, |y2-y1|))chebyshev_distdistance.chebyshev(point1,point2)print(f切比雪夫距离:{chebyshev_dist})方法五不开方的距离用于比较如果你只是需要比较距离大小不需要实际距离值可以省略开方操作以提高性能defdistance_squared(p1,p2):计算距离的平方不开方x1,y1p1 x2,y2p2return(x2-x1)**2(y2-y1)**2point1(1,2)point2(4,6)point3(5,5)dist2_1distance_squared(point1,point2)# 25dist2_2distance_squared(point1,point3)# 25# 比较时不需要开方ifdist2_1dist2_2:print(point2 更近)elifdist2_1dist2_2:print(point3 更近)else:print(距离相等)完整示例包含 3D 点importmathdefcalculate_distance(p1,p2):支持任意维度的点iflen(p1)!len(p2):raiseValueError(两点维度必须相同)# 计算各维度差值的平方和sum_of_squaressum((a-b)**2fora,binzip(p1,p2))# 开方returnmath.sqrt(sum_of_squares)# 2D 点p1_2d(1,2)p2_2d(4,6)print(f2D 距离:{calculate_distance(p1_2d,p2_2d)})# 3D 点p1_3d(1,2,3)p2_3d(4,6,8)print(f3D 距离:{calculate_distance(p1_3d,p2_3d)})# 使用 math.dist (Python 3.8)print(f3D 距离 (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()代码最简洁且性能好

更多文章