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

Javascript

JS Math.exp 用法:e 的 x 次方

JS Math.exp 用法:e 的 x 次方 特色圖片

Math.exp() 是 JavaScript 計算指數函數 eˣ 的靜態方法:傳入一個數字 x,回傳 e 的 x 次方。

e 是自然對數的底數,約等於 2.718281828459045,也就是 Math.E。白話一點,Math.exp(2) 就是 e × e。

語法

Math.exp(x)
  • x:一個數字。
  • 回傳值:一個不是負數的數字,代表 eˣ。

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

基本用法

console.log(Math.exp(-Infinity)); // 0
console.log(Math.exp(-1));        // 0.36787944117144233
console.log(Math.exp(0));         // 1
console.log(Math.exp(1));         // 2.718281828459045
console.log(Math.exp(Infinity));  // Infinity

整理成對照表:

輸入結果
-Infinity0
-10.36787944117144233
01
12.718281828459045
27.38905609893065
InfinityInfinity

輸入太大時,結果超過數字可表示的上限,會變成 Infinity:

console.log(Math.exp(709)); // 8.218407461554972e+307
console.log(Math.exp(710)); // Infinity

與 Math.E 的關係

Math.exp(1) 就是 e:

console.log(Math.E);                    // 2.718281828459045
console.log(Math.exp(1) === Math.E);    // true

算 e 的 x 次方時,用 Math.exp(x) 比 Math.E ** x 可靠,因為後者在某些輸入會多一點誤差:

console.log(Math.exp(2));    // 7.38905609893065
console.log(Math.E ** 2);    // 7.3890560989306495

與 Math.log 互為反函數

Math.log() 是自然對數,Math.exp() 是它的反函數:

console.log(Math.log(Math.exp(3))); // 3
console.log(Math.exp(Math.log(5))); // 5

x 很接近 0 時改用 Math.expm1

MDN 提醒:e 的「非常接近 0 的次方」會非常接近 1,直接相減容易損失精度。這時改用 Math.expm1()(計算 eˣ − 1),可以得到精度高得多的小數部分:

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

實用範例:指數衰減與 sigmoid

隨時間以固定比例遞減的量,可以用 N₀ × e^(−k × t) 計算:

const decay = (n0, k, t) => n0 * Math.exp(-k * t);

console.log(decay(100, 0.1, 5)); // 60.653065971263345

S 形曲線的 sigmoid 函式,也可以用 Math.exp() 寫成:

const sigmoid = (x) => 1 / (1 + Math.exp(-x));

console.log(sigmoid(0));  // 0.5
console.log(sigmoid(2));  // 0.8807970779778823
console.log(sigmoid(-2)); // 0.11920292202211755

注意事項

  1. 結果不會是負數:Math.exp() 的結果永遠大於或等於 0。
  2. 成長很快:輸入稍大就可能得到 Infinity。
  3. 接近 0 的差值用 Math.expm1():避免相減時損失精度。
  4. 精度依引擎而異:MDN 說明 Math 的許多函式精度依實作而異,不同環境的結果最後幾位可能不同,溢位的臨界值也可能不同。

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

參考資料與延伸閱讀

發佈留言