試一試
console.log(Math.expm1(0));
// Expected output: 0
console.log(Math.expm1(1));
// Expected output: 1.718281828459045
console.log(Math.expm1(-1));
// Expected output: -0.6321205588285577
console.log(Math.expm1(2));
// Expected output: 6.38905609893065
語法
js
Math.expm1(x)
引數
x-
一個數字。
返回值
一個代表 ex - 1 的數字,其中 e 是 自然對數的底數。
描述
對於非常小的 x 值,將 1 相加可能會降低甚至消除精度。JS 中使用的雙精度浮點數大約提供 15 位數字的精度。1 + 1e-15 = 1.000000000000001,但 1 + 1e-16 = 1.000000000000000,因此在該算術運算中恰好為 1.0,因為超過 15 位數字會被四捨五入。
當你計算(其中 x 是非常接近 0 的數字)時,你應該得到一個非常接近 1 + x 的結果,因為。如果你計算 Math.exp(1.1111111111e-15) - 1,你應該得到一個接近 1.1111111111e-15 的結果。然而,由於 Math.exp 結果中最高有效數字是各位上的 1,最終值變成了 1.1102230246251565e-15,只有 3 位數字是正確的。如果你改為計算 Math.expm1(1.1111111111e-15),你將得到一個更精確的結果,1.1111111111000007e-15,具有 11 位正確的精度。
由於 expm1() 是 Math 的靜態方法,你總是使用 Math.expm1() 來呼叫它,而不是透過你建立的 Math 物件方法(Math 不是一個建構函式)。
示例
使用 Math.expm1()
js
Math.expm1(-Infinity); // -1
Math.expm1(-1); // -0.6321205588285577
Math.expm1(-0); // -0
Math.expm1(0); // 0
Math.expm1(1); // 1.718281828459045
Math.expm1(Infinity); // Infinity
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-math.expm1 |
瀏覽器相容性
載入中…