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?
In fact, any base can be used, not just *e* or 2, as long as both logarithms use the same base.
Joey
2010-06-10 23:40:07
Added an image with the formula and linked to Wikipedia if you don't mind.
Anurag
2010-06-10 23:40:28
thanks to you both!
shogun
2010-06-10 23:41:49
great, thanks @Anurag.
Peter
2010-06-11 00:46:45
+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
2010-06-10 23:35:47
+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
2010-06-10 23:37:02
[`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
2010-06-10 23:40:10
thanks CMS. Proves one should test things before one feels "inspired." I'll go back to the drawing pad.
artlung
2010-06-10 23:41:12
+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
2010-06-10 23:38:45