紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS Math.atanh 用法:反雙曲正切與參數範圍

JS Math.atanh 用法:反雙曲正切與參數範圍 特色圖片

Math.atanh() 是 JavaScript 計算反雙曲正切(inverse hyperbolic tangent)的靜態方法:傳入一個介於 -1 與 1 之間的數字,回傳對應的反雙曲正切值。

白話一點,雙曲正切 Math.tanh() 是「給一個數,算出雙曲正切」;Math.atanh() 則是反過來「已知雙曲正切,求原本的數」。

語法

Math.atanh(x)
  • x:介於 -1 與 1(含)之間的數字。
  • 回傳值:x 的反雙曲正切。x 是 1 時回傳 Infinity,是 -1 時回傳 -Infinity,小於 -1 或大於 1 時回傳 NaN。

MDN 給的數學定義:對所有 x 介於 -1 與 1 之間(不含端點),Math.atanh(x) 等於唯一一個滿足 tanh(y) = x 的 y,也等於 ½ × ln((1 + x) / (1 − x))。

基本用法

console.log(Math.atanh(-2));  // NaN
console.log(Math.atanh(-1));  // -Infinity
console.log(Math.atanh(-0));  // -0
console.log(Math.atanh(0));   // 0
console.log(Math.atanh(0.5)); // 0.5493061443340548
console.log(Math.atanh(1));   // Infinity
console.log(Math.atanh(2));   // NaN

整理成對照表:

輸入結果
小於 -1 或大於 1,例如 -2、2NaN
-1-Infinity
-0-0
00
0.50.5493061443340548
1Infinity

兩個端點 -1 與 1 本身不會得到 NaN,而是 -Infinity 與 Infinity;只要超出範圍,即使只差一點點,結果就是 NaN:

console.log(Math.atanh(0.9999999999)); // 11.859499013855018
console.log(Math.atanh(1.0000000001)); // NaN

對照定義公式

用 MDN 的公式 ½ × ln((1 + x) / (1 − x)) 自己算一次:

console.log(0.5 * Math.log((1 + 0.5) / (1 - 0.5))); // 0.5493061443340548
console.log(Math.atanh(0.5));                       // 0.5493061443340548

與 Math.tanh 互為反函數

console.log(Math.tanh(Math.atanh(0.5))); // 0.49999999999999994
console.log(Math.atanh(Math.tanh(1)));   // 0.9999999999999999

來回運算後得到非常接近原值的數,最後的小數位是浮點數誤差。需要比較時,用差距小於某個門檻判斷,不要用 ===。

注意事項

  1. 參數要在 -1 到 1 之間:超出範圍不會報錯,只會回傳 NaN,後續運算要留意。
  2. 端點是無限大:剛好是 1 或 -1 時回傳 Infinity 或 -Infinity,不是 NaN。
  3. 精度依引擎而異:MDN 說明 Math 的許多函式精度依實作而異,不同環境的結果最後幾位可能不同。
  4. 舊環境相容性:如果要支援很舊的瀏覽器,可查 MDN 頁面上的相容性表,並參考頁面列出的 polyfill。

補充說明:範例輸出為 Node.js v22.20.0 的執行結果。同系列的反雙曲函數還有 Math.acosh() 與 Math.asinh(),雙曲函數有 Math.sinh()、Math.cosh()、Math.tanh()。

參考資料與延伸閱讀

發佈留言