Math.log()

Math.log() 静态方法返回数字的自然对数(以 e 为底)。那是

¥The Math.log() static method returns the natural logarithm (base e) of a number. That is

x > 0 , 𝙼𝚊𝚝𝚑.𝚕𝚘𝚐 ( 𝚡 ) = ln ( x ) = the unique  y  such that  e y = x \forall x > 0,;\mathtt{\operatorname{Math.log}(x)} = \ln(x) = \text{the unique } y \text{ such that } e^y = x

Try it

语法

¥Syntax

js
Math.log(x)

参数

¥Parameters

x

大于或等于 0 的数字。

返回值

¥Return value

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

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

描述

¥Description

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

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

如果需要 2 或 10 的自然对数,请使用常量 Math.LN2Math.LN10。如果需要以 2 或 10 为底的对数,请使用 Math.log2()Math.log10()。如果你需要其他底数的对数,请使用 Math.log(x) / Math.log(otherBase),如下例所示;你可能需要预先计算 1 / Math.log(otherBase),因为 Math.log(x) * constant 中的乘法要快得多。

¥If you need the natural log of 2 or 10, use the constants Math.LN2 or Math.LN10. If you need a logarithm to base 2 or 10, use Math.log2() or Math.log10(). If you need a logarithm to other bases, use Math.log(x) / Math.log(otherBase) as in the example below; you might want to precalculate 1 / Math.log(otherBase) since multiplication in Math.log(x) * constant is much faster.

请注意,非常接近 1 的正数可能会导致精度损失,并使其自然对数不太准确。在这种情况下,你可能需要使用 Math.log1p

¥Beware that positive numbers very close to 1 can suffer from loss of precision and make its natural logarithm less accurate. In this case, you may want to use Math.log1p instead.

示例

¥Examples

使用 Math.log()

¥Using Math.log()

js
Math.log(-1); // NaN
Math.log(-0); // -Infinity
Math.log(0); // -Infinity
Math.log(1); // 0
Math.log(10); // 2.302585092994046
Math.log(Infinity); // Infinity

使用具有不同基数的 Math.log()

¥Using Math.log() with a different base

以下函数返回 yx 为底的对数(即 log x y< /mi> <注释编码="TeX">\log_x y</注释></语义></数学>):

¥The following function returns the logarithm of y with base x (i.e. log x y \log_x y ):

js
function getBaseLog(x, y) {
  return Math.log(y) / Math.log(x);
}

如果运行 getBaseLog(10, 1000),由于浮点舍入,它会返回 2.9999999999999996,但仍然非常接近实际答案 3。

¥If you run getBaseLog(10, 1000), it returns 2.9999999999999996 due to floating-point rounding, but still very close to the actual answer of 3.

规范

Specification
ECMAScript Language Specification
# sec-math.log

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看