如何在 Javascript 中执行不同的底对数函数?

发布于 2024-12-21 11:50:08 字数 342 浏览 2 评论 0原文

这个问题是在考虑到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

︶葆Ⅱㄣ 2024-12-28 11:50:08

您可以使用对数基数变化公式

log[a](n) = log[b](n) / log[b](a)

因此,为了获得以 512 为底的 log(2),请使用:

function log(b, n) {
    return Math.log(n) / Math.log(b);
}

alert(log(2, 512));

注意上面的 Math.log 使用自然对数基数;即,在数学上它会被写成ln

You can use the logarithm base change formula:

log[a](n) = log[b](n) / log[b](a)

So in order to get log(2) base 512, use:

function log(b, n) {
    return Math.log(n) / Math.log(b);
}

alert(log(2, 512));

Note that Math.log above uses the natural log base; i.e., it would be written as ln mathematically.

玩心态 2024-12-28 11:50:08

我今天在谷歌上找到了这个答案作为第一个结果,如果其他人也找到了它,那就有一个小错误。正确版本如下:

function log(b, n) {  
    return Math.log(n) / Math.log(b);  
}

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:

function log(b, n) {  
    return Math.log(n) / Math.log(b);  
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文