Math.asinh() 是 JavaScript 計算反雙曲正弦(inverse hyperbolic sine)的靜態方法:傳入任何一個數字,回傳對應的反雙曲正弦值。
白話一點,雙曲正弦 Math.sinh() 是「給一個數,算出雙曲正弦」;Math.asinh() 則是反過來「已知雙曲正弦,求原本的數」。
語法
Math.asinh(x)
x:一個數字,沒有範圍限制。- 回傳值:
x的反雙曲正弦。
MDN 給的數學定義:Math.asinh(x) 等於唯一一個滿足 sinh(y) = x 的 y,也等於 ln(x + √(x² + 1))。
asinh() 是 Math 的靜態方法,一律寫成 Math.asinh(),不需要也不能 new Math()。
基本用法
console.log(Math.asinh(-Infinity)); // -Infinity
console.log(Math.asinh(-1)); // -0.881373587019543
console.log(Math.asinh(-0)); // -0
console.log(Math.asinh(0)); // 0
console.log(Math.asinh(1)); // 0.881373587019543
console.log(Math.asinh(Infinity)); // Infinity
整理成對照表:
| 輸入 | 結果 |
|---|---|
-Infinity | -Infinity |
-1 | -0.881373587019543 |
-0 | -0 |
0 | 0 |
1 | 0.881373587019543 |
Infinity | Infinity |
-1 與 1 的結果只差正負號,正負對稱的輸入會得到正負對稱的結果:
console.log(Math.asinh(5)); // 2.3124383412727525
console.log(Math.asinh(-5)); // -2.3124383412727525
對照定義公式
用 MDN 的公式 ln(x + √(x² + 1)) 自己算一次:
console.log(Math.log(2 + Math.sqrt(2 ** 2 + 1))); // 1.4436354751788103
console.log(Math.asinh(2)); // 1.4436354751788103
換成 x = 1,兩種算法的最後一位就不同了:
console.log(Math.log(1 + Math.sqrt(1 ** 2 + 1))); // 0.8813735870195429
console.log(Math.asinh(1)); // 0.881373587019543
這是浮點數的運算誤差,用公式手算與直接呼叫 Math.asinh() 不一定逐位相同。
與 Math.sinh 互為反函數
console.log(Math.sinh(Math.asinh(2))); // 1.9999999999999998
console.log(Math.asinh(Math.sinh(1))); // 1
來回運算後得到非常接近原值的數,最後的小數位可能有浮點數誤差。需要比較時,用差距小於某個門檻判斷,不要用 ===。
注意事項
- 任何數字都能傳:和
Math.acosh()(參數至少 1)、Math.atanh()(參數在 -1 到 1 之間)不同,Math.asinh()的參數沒有範圍限制;傳入NaN時結果也是NaN。 - 精度依引擎而異:MDN 說明
Math的許多函式精度依實作而異,不同環境的結果最後幾位可能不同。 - 舊環境相容性:如果要支援很舊的瀏覽器,可查 MDN 頁面上的相容性表,並參考頁面列出的 polyfill。
補充說明:範例輸出為 Node.js v22.20.0 的執行結果。同系列的反雙曲函數還有
Math.acosh()與Math.atanh(),雙曲函數有Math.sinh()、Math.cosh()、Math.tanh()。
發佈留言