最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - How can you perform varying base logarithmic functions in Javascript? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Dec 13, 2011 at 16:17 AejayAejay 9299 silver badges19 bronze badges 1
  • Possible duplicate of: Any way to specify the base of math.log() in javascript? – hippietrail Commented Oct 28, 2012 at 3:53
Add a comment  | 

2 Answers 2

Reset to default 16

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.

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);  
}
发布评论

评论列表(0)

  1. 暂无评论