如何在 Javascript 中执行不同的底对数函数?
这个问题是在考虑到 Node.js 服务器时提出的,但我将问题表述为“javascript”,因为我可能也会对客户端脚本使用相同的逻辑。
问题是:给定一组 x 值,y 需要以对数方式缩放。 Math 对象执行自然对数 [ln(x)
],但不提供用于指定对数底数的接口。
对于一个具体的例子,我需要找到以下内容:
log[512](2)
应该返回 .1111~
但是,我没有看到允许我完成此操作的接口,我也不能似乎找到了一个公开日志基础选项的库。当然,这是一个常见问题并且有解决方案,但我的搜索只找到了不同/不相关问题的解决方案。有想法吗?
This problem is being asked with a node.js server in mind, but I stated the question as "javascript" because I will likely use this same logic for a client-side script, as well.
Here's the problem: given a set of x values, y needs to scale in a logarithmic way. The Math object performs a natural log [ln(x)
], but does not provide an interface for specifying the base of the logarithm.
For a specific example, I need to find the following:
log[512](2)
Which should return .1111~
However, I do not see an interface that allows me to accomplish this, nor can I seem to find a library that exposes an option for the log's base. Surely this is a common problem and has a solution, but my searching has only found solutions for different/unrelated problems. Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用对数基数变化公式:
因此,为了获得以 512 为底的 log(2),请使用:
注意上面的
Math.log
使用自然对数基数;即,在数学上它会被写成ln
。You can use the logarithm base change formula:
So in order to get log(2) base 512, use:
Note that
Math.log
above uses the natural log base; i.e., it would be written asln
mathematically.我今天在谷歌上找到了这个答案作为第一个结果,如果其他人也找到了它,那就有一个小错误。正确版本如下:
I found this answer as a first result in google today, and if anyone else finds it too, there's a small mistake. The correct version is as follows: