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

Javascript

JS Math.expm1 用法:e 的 x 次方減 1

JS Math.expm1 用法:e 的 x 次方減 1 特色圖片

Math.expm1() 是 JavaScript 計算 eˣ − 1 的靜態方法:傳入一個數字 x,回傳 e 的 x 次方再減 1。

名稱的 expm1 可以讀成 exp minus 1。白話一點,它就是「Math.exp(x) - 1」的精準版,x 很接近 0 時差別最明顯。

語法

Math.expm1(x)
  • x:一個數字。
  • 回傳值:一個數字,代表 eˣ − 1,其中 e 是自然對數的底數。

expm1() 是 Math 的靜態方法,一律寫成 Math.expm1(),不需要也不能 new Math()。

基本用法

console.log(Math.expm1(-Infinity)); // -1
console.log(Math.expm1(-1));        // -0.6321205588285577
console.log(Math.expm1(-0));        // -0
console.log(Math.expm1(0));         // 0
console.log(Math.expm1(1));         // 1.718281828459045
console.log(Math.expm1(2));         // 6.38905609893065
console.log(Math.expm1(Infinity));  // Infinity

整理成對照表:

輸入結果
-Infinity-1
-1-0.6321205588285577
-0-0
00
11.718281828459045
InfinityInfinity

輸入 -0 時,結果也是 -0,不會被改成 0。

為什麼不直接寫 Math.exp(x) – 1

MDN 說明,JavaScript 使用的倍精度浮點數(double float)大約有 15 位的有效數字。x 很接近 0 時,eˣ 會非常接近 1,加減 1 的過程會讓有效數字損失,甚至完全消失。

MDN 的例子是 x 等於 1.1111111111e-15:

console.log(Math.exp(1.1111111111e-15) - 1); // 1.1102230246251565e-15
console.log(Math.expm1(1.1111111111e-15));   // 1.1111111111000007e-15

依 MDN 的說明,第一種寫法只有前 3 位正確;Math.expm1() 的結果有 11 位正確。

再看幾組更小的輸入:

console.log(Math.exp(1e-10) - 1); // 1.000000082740371e-10
console.log(Math.expm1(1e-10));   // 1.00000000005e-10
console.log(Math.exp(1e-15) - 1); // 1.1102230246251565e-15
console.log(Math.expm1(1e-15));   // 1.0000000000000007e-15
console.log(Math.exp(1e-16) - 1); // 0
console.log(Math.expm1(1e-16));   // 1e-16

x 等於 1e-16 時,Math.exp(x) - 1 已經得到 0,Math.expm1(x) 仍然回傳 1e-16。

與 Math.log1p 互為反函數

Math.log1p(x) 計算 ln(1 + x),和 Math.expm1() 是一組互為反函數的方法:

console.log(Math.expm1(Math.log1p(0.25))); // 0.25
console.log(Math.log1p(Math.expm1(0.25))); // 0.25

兩者都是為了避開「加 1」或「減 1」造成的精度損失,成對使用最合適。

實用範例:連續成長率換成一期成長比例

連續成長率 r 對應的一期成長比例是 eʳ − 1。r 很小時,用 Math.expm1() 計算比較準確:

const growth = (r) => Math.expm1(r);

console.log(growth(0.05));  // 0.05127109637602404
console.log(growth(1e-5));  // 0.000010000050000166668

對照 Math.exp(1e-5) - 1,結果是 0.000010000050000069649,只有前幾位和上面一致。

注意事項

  1. x 很接近 0 才有明顯差別:x 較大時,Math.exp(x) - 1 與 Math.expm1(x) 通常沒有差別。
  2. 保留 -0:Math.expm1(-0) 回傳 -0。
  3. 搭配 Math.log1p:要把結果換回原本的數字,用 Math.log1p()。
  4. 精度依引擎而異:MDN 說明 Math 的許多函式精度依實作而異,不同環境的結果最後幾位可能不同。

補充說明:範例輸出為 Node.js v22.20.0 的執行結果。相關方法還有 Math.E、Math.exp()、Math.log()、Math.log10()、Math.log1p()、Math.log2() 與 Math.pow()。

參考資料與延伸閱讀

發佈留言