DIV CSS 佈局教程網

Math.exp():JavaScript 裡計算 e 的 x 次方
編輯:JavaScript基礎知識     

這個方法在做什麼

Math.exp(x) 的任務很單純:回傳 e 的 x 次冪,也就是自然指數值。這裡的 e 是自然對數的底數,近似值為 2.71828。如果你在計算連續複利、衰減曲線、常微分方程數值解,或是需要把對數尺度還原回線性尺度,就會 frequent 用到它。

語法與參數

Math.exp(x);

參數 x 可以是任何數值或能轉成數值的表達式,作為指數使用。

回傳值:e 的 x 次冪。若 x 為正無窮大則得到 Infinity,若為負無窮大則得到 0;傳入非數值會得到 NaN。

實際範例

<script type="text/javascript">
document.write(Math.exp(2));    // 7.38905609893065
document.write("<br>");
document.write(Math.exp(1));    // 2.718281828459045
document.write("<br>");
document.write(Math.exp(-2));   // 0.1353352832366127
document.write("<br>");
document.write(Math.exp(0.25)); // 1.2840254166877414
document.write("<br>");
document.write(Math.exp(-0.46));// 0.631283645506926
</script>

幾個實用提醒

指數為 1 時,結果正好等於 Math.E,這也是驗證環境是否正常的最簡單方式。另外,指數運算也可以用 Math.pow(Math.E, x) 達成同樣效果,但 Math.exp() 語意更清楚、執行也更直接。若你需要的是任意底數的次方(例如 2 的 10 次方),那應該改用 Math.pow();兩者別搞混。

要注意浮點數精度的問題。當 x 很大(例如超過 710)時,結果會溢位成 Infinity;當 x 很小(例如小於 -745)時,結果會下溢為 0。若你的運算會落在這些極端區間,建議改用對數空間計算,再搭配 Math.log() 還原。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved