首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python math.hypot():計算歐幾里得距離的標準做法

     編輯:更多程式設計知識

在二維平面幾何、向量運算、遊戲開發或資料科學中,計算兩點間的直線距離(歐幾里得距離)是極高頻需求。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  不會溢位

實戰應用場景

1. 兩點距離


def distance(p1, p2):
    return math.hypot(p2[0] - p1[0], p2[1] - p1[1])

print(distance((0, 0), (3, 4)))  # 5.0

2. 向量長度(模)


vec = (6, 8)
magnitude = math.hypot(*vec)  # 10.0

3. 遊戲開發:圓形碰撞檢測


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)

4. 多維擴展(Python 3.8+)


# 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+ 原生支援需自行迴圈

NumPy 版本:向量化批次計算


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()。
  • Python < 3.8 多維:請用 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() 是計算歐幾里得距離的「標準答案」,簡潔、穩定、高效,建議在所有專案中取代手寫平方根公式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved