如何在 JavaScript 中指定 Math.log() 的基数?
我需要 JavaScript 的 log
函数,但它需要以 10 为基数。我看不到任何相关列表,所以我假设这是不可能的。有没有数学奇才知道这个问题的解决方案?
I need a log
function for JavaScript, but it needs to be base 10. I can't see any listing for this, so I'm assuming it's not possible. Are there any math wizards out there who know a solution for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
“改变基础”公式/身份
由于 JavaScript 中的
Math.log(x)
返回x
的自然对数(与 < em>ln(x)),对于基数 10,您可以除以Math.log(10)
(与 ln(10) 相同):Math.LN10
是Math.log(10)
的内置预计算常量,因此该函数本质上等同于:"Change of Base" Formula / Identity
Since
Math.log(x)
in JavaScript returns the natural logarithm ofx
(same as ln(x)), for base 10 you can divide byMath.log(10)
(same as ln(10)):Math.LN10
is a built-in precomputed constant forMath.log(10)
, so this function is essentially identical to:很简单,只需除以 log(10) 即可更改底数。甚至还有一个常量可以帮助你,
它与以下内容相同:
Easy, just change the base by dividing by the log(10). There is even a constant to help you
which is the same as:
您可以简单地将值的对数与所需底数的对数相除,也可以重写 Math.log 方法以接受可选的底数参数:
You can simply divide the logarithm of your value, and the logarithm of the desired base, also you could override the
Math.log
method to accept an optional base argument:https://en.wikipedia.org/wiki/Logarithm#Change_of_base
https://en.wikipedia.org/wiki/Logarithm#Change_of_base
这里的答案会导致明显的精度问题,并且在某些用例中不可靠
the answer here would cause obvious precision problem and is not reliable in some use cases
然后你可以做
注意:最初我想这样做
Math.prototype.log10 = ...
来做到这一点,但是用户CMS指出Math不是这样工作的,所以我编辑掉了.prototype
部分。Then you can do
NOTE: Initially I thought to do
Math.prototype.log10 = ...
to do this, but user CMS pointed out that Math doesn't work this way, so I edited out the.prototype
part.FF 25+ 支持
Math.log10
方法。您可以使用polyfill:
MDN 列出了 支持的浏览器。
FF 25+ supports a
Math.log10
method. You may to use polyfill:MDN lists the supported browsers.
Math.log10(x)
最上面的答案对于任意基数都可以,但问题是关于对数基数 10,并且
Math.log10(x)
已自 2015 年以来所有浏览器的标准。**IE 除外,如果出于某种原因这对您很重要的话。
Math.log10(x)
The top answer is fine for an arbitrary base, but the question is regarding log base 10, and
Math.log10(x)
has been standard across all browsers since 2015.**Except IE, if that's important to you for some reason.
如果您有一个数字 x,那么使用
Math.log(x)
本质上就是 lnx。要将其转换为 e 以外的基数,可以使用以下函数:
If you have a number x, then use of
Math.log(x)
would essentially be lnx.To convert it to a base other than e, you can use the following function :
对于基数 10,请使用 Math.log10()。
请参阅文档:https://developer. mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log10
For base 10 use
Math.log10()
.See docs at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log10