Math.log1p()

Math.log1p() 静态方法返回 1 + x 的自然对数(以 e 为底),其中 x 是参数。那是:

¥The Math.log1p() static method returns the natural logarithm (base e) of 1 + x, where x is the argument. That is:

x > 1 , 𝙼𝚊𝚝𝚑.𝚕𝚘𝚐𝟷𝚙 ( 𝚡 ) = ln ( 1 + x ) \forall x > -1,;\mathtt{\operatorname{Math.log1p}(x)} = \ln(1 + x)

Try it

语法

¥Syntax

js
Math.log1p(x)

参数

¥Parameters

x

大于或等于-1 的数字。

返回值

¥Return value

x + 1 的自然对数(以 e 为底)。如果 x 为 -1,则返回 -Infinity。如果是 x < -1,则返回 NaN

¥The natural logarithm (base e) of x + 1. If x is -1, returns -Infinity. If x < -1, returns NaN.

描述

¥Description

对于非常小的 x 值,加 1 会降低或消除精度。JS 中使用的双浮点可为你提供大约 15 位的精度。1 + 1e-15 = 1.000000000000001,但 1 + 1e-16 = 1.000000000000000,因此在该算术中恰好是 1.0,因为超过 15 的数字会四舍五入。

¥For very small values of x, adding 1 can reduce or eliminate precision. The double floats used in JS give you about 15 digits of precision. 1 + 1e-15 = 1.000000000000001, but 1 + 1e-16 = 1.000000000000000 and therefore exactly 1.0 in that arithmetic, because digits past 15 are rounded off.

当你计算 log(1 + x)(其中 x 是一个小的正数)时,你应该得到非常接近 x 的答案,因为 lim x<mo 有弹性="false">→ 0 log <mostretchy="false">( 1 + x</ mi><mostretchy="false">) x = 1 < 注释编码="TeX">\lim_{x \to 0}\frac{\log(1+x)}{x} = 1</注释></语义></数学>。如果计算 Math.log(1 + 1.1111111111e-15),你应该得到接近 1.1111111111e-15 的答案。相反,你最终会取 1.00000000000000111022 的对数(四舍五入是二进制的,所以有时会变得很难看),并得到答案 1.11022…e-15,只有 3 个正确的数字。相反,如果你计算 Math.log1p(1.1111111111e-15),你将得到更准确的答案 1.1111111110999995e-15,其精度为 15 位正确数字(在本例中实际上为 16 位)。

¥When you calculate log(1 + x) where x is a small positive number, you should get an answer very close to x, because lim x 0 log ( 1 + x ) x = 1 \lim_{x \to 0} \frac{\log(1+x)}{x} = 1 . If you calculate Math.log(1 + 1.1111111111e-15), you should get an answer close to 1.1111111111e-15. Instead, you will end up taking the logarithm of 1.00000000000000111022 (the roundoff is in binary, so sometimes it gets ugly), and get the answer 1.11022…e-15, with only 3 correct digits. If, instead, you calculate Math.log1p(1.1111111111e-15), you will get a much more accurate answer 1.1111111110999995e-15, with 15 correct digits of precision (actually 16 in this case).

如果 x 的值小于 -1,则返回值始终为 NaN

¥If the value of x is less than -1, the return value is always NaN.

因为 log1p()Math 的静态方法,所以你始终将其用作 Math.log1p(),而不是用作你创建的 Math 对象的方法(Math 不是构造函数)。

¥Because log1p() is a static method of Math, you always use it as Math.log1p(), rather than as a method of a Math object you created (Math is not a constructor).

示例

¥Examples

使用 Math.log1p()

¥Using Math.log1p()

js
Math.log1p(-2); // NaN
Math.log1p(-1); // -Infinity
Math.log1p(-0); // -0
Math.log1p(0); // 0
Math.log1p(1); // 0.6931471805599453
Math.log1p(Infinity); // Infinity

规范

Specification
ECMAScript Language Specification
# sec-math.log1p

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看