6

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?

Aejay
  • 909
  • 9
  • 19
  • Possible duplicate of: [Any way to specify the base of math.log() in javascript?](http://stackoverflow.com/questions/3019278) – hippietrail Oct 28 '12 at 03:53

2 Answers2

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.

Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
  • 2
    the javascript function would look like `function log(base, number) { return Math.ln(number) / Math.ln(base); }` – Dan D. Dec 13 '11 at 16:23
  • So, this ended up being a math question. Man, it's been years since I've had to work logarithm problems. Thanks for the quick fix. – Aejay Dec 13 '11 at 16:24
  • Very true, I forgot this was a JS question and not just a math one. Thanks! – Platinum Azure Dec 13 '11 at 16:25
  • 1
    Actually, I just tried it out and it really should be `log`, not `ln`. I feel awful for letting this sit for over a year. – Platinum Azure Dec 27 '12 at 17:20
  • Has it been a year already? Wow. Seems like I just asked this a month ago. On a side note, it's strange how log refers to ln in programming; I'm sure it has caught up quite a few programmers in frustrated debugging. The fact that you have to go out of your way to find or recreate log[10] can be annoying. – Aejay Dec 28 '12 at 18:56
5

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);  
}
mmateoo
  • 101
  • 1
  • 5