views:

145

answers:

4

I need a log function in my javascript but it needs to be base 10, I can't see any listing for this so I'm assuming it's not possible... any math wizards out there know of an approach for this? Or maybe I'm missing something and there is a way?

+7  A: 

Logarithm for base 10

function log10(val) {
  return Math.log(val) / Math.log(10);
}
Peter
In fact, any base can be used, not just *e* or 2, as long as both logarithms use the same base.
Joey
Added an image with the formula and linked to Wikipedia if you don't mind.
Anurag
thanks to you both!
shogun
great, thanks @Anurag.
Peter
+4  A: 

Easy, just change the base by dividing by the log(10). There is even a constant to help you

Math.log(num) / Math.LN10;

which is the same as:

Math.log(num) / Math.log(10);
bramp
+1  A: 
Math.log10 = function(n) {
    return (Math.log(n)) / (Math.log(10));
}

Then you can do

Math.log10(your_number);

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.

artlung
[`Math`](https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Math) is an object, not a constructor function, therefore it doesn't have a `prototype` property.
CMS
thanks CMS. Proves one should test things before one feels "inspired." I'll go back to the drawing pad.
artlung
@artlung: Just remove the `.prototype` part ;)
CMS
Removed, thanks @CMS!
artlung
+4  A: 

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:

Math.log = (function() {
  var log = Math.log;
  return function(n, base) {
    return log(n)/(base ? log(base) : 1);
  };
})();

Math.log(5, 10);
CMS