Math.log()
Math.log() 静态方法返回数字的自然对数(以 e 为底)。那是
¥The Math.log() static method returns the natural logarithm (base e) of a number. That is
Try it
语法
参数
返回值
描述
¥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.LN2 或 Math.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.
示例
使用 Math.log()
使用具有不同基数的 Math.log()
¥Using Math.log() with a different base
以下函数返回 y 以 x 为底的对数(即
¥The following function returns the logarithm of y with base x (i.e.
):
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 |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also