萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python math.hypot():計算歐幾里得範數(直角三角形斜邊)

math.hypot(x, y) 返回 sqrt(x*x + y*y),即直角三角形兩直角邊為 x、y 時的斜邊長度,亦即向量 (x, y) 的 L2 範數。Python 3.8+ 支援多維:hypot(*coordinates)。

語法

math.hypot(x, y)

範例

>> import math
>>> math.hypot(3, 2)
3.605551275463989
>>> math.hypot(-3, 3)
4.242640687119285
>>> math.hypot(0, 2)
2.0

應用場景

  • 二維平面距離計算:dist = hypot(x2-x1, y2-y1)。
  • 向量模長正規化。
  • 避免中間結果溢位(內部縮放算法)。

多維擴展(Python 3.8+)

>> math.hypot(1, 2, 2)   # 3D 向量模長
3.0
>>> math.hypot(*[3,4,12])  # 13.0
copyright © 萬盛學電腦網 all rights reserved