Math.hypot() 是 JavaScript 計算平方和的平方根的靜態方法:傳入任意個數字,回傳每個數字平方後相加,再開平方根的結果。
名稱 hypot 取自英文 hypotenuse,也就是直角三角形的斜邊。Math.hypot(3, 4) 就是斜邊長 5。
語法
Math.hypot()
Math.hypot(value1)
Math.hypot(value1, value2)
Math.hypot(value1, value2, /* …, */ valueN)
value1、…、valueN:數字,可以給任意多個。- 回傳值:所有參數平方和的平方根。
hypot() 是 Math 的靜態方法,一律寫成 Math.hypot(),不需要也不能 new Math()。
基本用法
console.log(Math.hypot(3, 4)); // 5
console.log(Math.hypot(5, 12)); // 13
console.log(Math.hypot(3, 4, 5)); // 7.0710678118654755
console.log(Math.hypot(-5)); // 5
兩個參數時,就是直角三角形兩股長度求斜邊,與畢氏定理(商高定理、勾股定理)相同。三個以上的參數,就是在三維以上空間求長度。
特殊輸入的結果
console.log(Math.hypot()); // 0
console.log(Math.hypot(NaN)); // NaN
console.log(Math.hypot(NaN, Infinity)); // Infinity
console.log(Math.hypot(3, 4, "foo")); // NaN
console.log(Math.hypot(3, 4, "5")); // 7.0710678118654755
console.log(Math.hypot(-3)); // 3
整理成規則:
| 輸入 | 結果 |
|---|---|
| 不給參數,或參數全是 ±0 | 0 |
| 任何一個參數是 ±Infinity | Infinity |
沒有 Infinity,但有參數是或轉成 NaN | NaN |
字串 "5" | 轉成數字 5 |
Math.hypot(NaN, Infinity) 是 Infinity,因為有 Infinity 時優先回傳 Infinity。
只給一個參數時,Math.hypot() 等同於 Math.abs()。
兩點之間的距離
兩點的水平差與垂直差,就是直角三角形的兩股,直接丟給 Math.hypot():
const dist = (p, q) => Math.hypot(q.x - p.x, q.y - p.y);
console.log(dist({ x: 1, y: 1 }, { x: 4, y: 5 })); // 5
console.log(dist({ x: 0, y: 0 }, { x: -6, y: 8 })); // 10
這個距離稱為歐氏距離(Euclidean distance)。三維以上,直接多傳幾個差值:
console.log(Math.hypot(1, 2, 2)); // 3
展開陣列
參數個數不固定時,用展開運算子把陣列傳進去:
const vals = [3, 4, 12];
console.log(Math.hypot(...vals)); // 13
為什麼不用 Math.sqrt 自己算
MDN 說明,Math.hypot() 能避開數字很大或很小時的溢位與歸零問題。大約超過 10 的 154 次方的數字,平方後會變成 Infinity;很小的數字平方後則會變成 0。
console.log(Math.sqrt(1e200 * 1e200 + 1e200 * 1e200)); // Infinity
console.log(Math.hypot(1e200, 1e200)); // 1.414213562373095e+200
console.log(Math.sqrt(1e-200 * 1e-200 + 1e-200 * 1e-200)); // 0
console.log(Math.hypot(1e-200, 1e-200)); // 1.414213562373095e-200
在一般大小的數字,Math.hypot() 與 Math.sqrt(x * x + y * y) 的結果相同:
console.log(Math.hypot(3, 4) === Math.sqrt(3 * 3 + 4 * 4)); // true
注意事項
- 參數個數沒有上限:兩個參數是斜邊,更多參數是更高維度的長度。
- 只有一個參數等同
Math.abs():負數會變成正數。 - 非數字會先轉成數字:
"5"變成 5,"foo"變成NaN。 Math.hypot.length是 2:MDN 說明這個值暗示它設計成至少處理兩個參數。- 精度依引擎而異:MDN 說明
Math的許多函式精度依實作而異,不同環境的結果最後幾位可能不同。
補充說明:範例輸出為 Node.js v22.20.0 的執行結果。相關方法還有
Math.abs()、Math.pow()與Math.sqrt()。
發佈留言