← 中文资源

简体中文版本

hypot 与 dist 计算直线距离

math.hypot 从分量直接算欧几里得长度,math.dist 算两点间直线距离:两者内部防溢出,大分量也不会丢精度,结果可互相印证。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

hypot 2d: 5.0
hypot 3d: 3.0
dist 2d: 5.0
dist 3d: 3.0
match: True

实现说明

演示用的数据放在这几个模块级绑定中:p1、p2。

使用要点

  • 跑完文件,输出里会留下标记——hypot 2d:、hypot 3d:、dist 2d:。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 状态都挂在模块顶层:p1、p2。

代码示例

import math

# hypot computes sqrt(x*x + y*y + ...) without overflow for big components
print("hypot 2d:", math.hypot(3, 4))
print("hypot 3d:", math.hypot(1, 2, 2))

# dist measures the straight-line distance between two points
p1 = (2, 3)
p2 = (5, 7)
print("dist 2d:", math.dist(p1, p2))

# dist also accepts higher-dimensional points of equal length
print("dist 3d:", math.dist((0, 0, 0), (1, 2, 2)))

# dist(a, b) equals hypot of the component differences
print("match:", math.dist(p1, p2) == math.hypot(5 - 2, 7 - 3))