在二維平面幾何、向量運算、遊戲開發或資料科學中,計算兩點間的直線距離(歐幾里得距離)是極高頻需求。Python math 模組提供 hypot(x, y) 函數,直接回傳 sqrt(x² + y²),不僅語意清晰,更能避免中間運算溢位或精度損失。本文完整說明用法、原理與實戰範例。
math.hypot(x: float, y: float) -> float
# Python 3.8+ 還支援多維:math.hypot(*coordinates)
x, y - 向量分量或座標差值。sqrt(x*x + y*y),非負浮點數。x*x 溢位(大數)或精度消失(小數)。
import math
print(math.hypot(3, 4)) # 5.0 (3-4-5 三角形)
print(math.hypot(-3, 3)) # 4.242640687119285
print(math.hypot(0, 2)) # 2.0
print(math.hypot(1e200, 1e200)) # 1.4142e+200 不會溢位
def distance(p1, p2):
return math.hypot(p2[0] - p1[0], p2[1] - p1[1])
print(distance((0, 0), (3, 4))) # 5.0
vec = (6, 8)
magnitude = math.hypot(*vec) # 10.0
def circles_collide(c1, r1, c2, r2):
"""c1, c2 為圓心座標 (x, y)"""
return math.hypot(c2[0] - c1[0], c2[1] - c1[1]) <= (r1 + r2)
print(circles_collide((0,0), 5, (8,0), 4)) # True (距離 8 <= 9)
# 3D 距離
print(math.hypot(1, 2, 2)) # 3.0 (sqrt(1+4+4))
# N 維
coords = [3, 4, 0, 0, 0]
print(math.hypot(*coords)) # 5.0
sqrt(x*x + y*y) 比較| 方面 | math.hypot | 手寫 sqrt(x²+y²) |
|---|---|---|
| 可讀性 | 語意明確 | 需心算公式 |
| 大數穩定性 | 內建縮放,不溢位 | 極易溢位 (如 1e200) |
| 小數精度 | 保護低位精度 | 可能下溢為 0 |
| 效能 | C 層實現,極快 | 相當,但需兩次乘法 |
| 維度擴充 | 3.8+ 原生支援 | 需自行迴圈 |
import numpy as np
pts1 = np.array([[0,0], [1,1], [3,4]])
pts2 = np.array([[3,4], [4,5], [0,0]])
dists = np.hypot(pts2[:,0] - pts1[:,0], pts2[:,1] - pts1[:,1])
print(dists) # [5. 5. 5.]
hypot(x, y) 對應 dx, dy 或 x, y 分量,順序不影響結果(平方和對稱)。round() 或 int()。math.sqrt(sum(c*c for c in coords)) 或 np.linalg.norm。
import math, sys
if __name__ == '__main__':
if len(sys.argv) != 3:
print('用法: python hypot_calc.py x y')
sys.exit(1)
x, y = map(float, sys.argv[1:])
print(f'hypot({x}, {y}) = {math.hypot(x, y):.6f}')
math.hypot() 是計算歐幾里得距離的「標準答案」,簡潔、穩定、高效,建議在所有專案中取代手寫平方根公式。