试一试
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 |
浏览器兼容性
加载中…