How can I specify the base for Math.log() in JavaScript?
"Change of Base" Formula / Identity
The numerical value for logarithm to the base 10 can be calculated with the following identity.
Since Math.log(x)
in JavaScript returns the natural logarithm of x
(same as ln(x)), for base 10 you can divide by Math.log(10)
(same as ln(10)):
function log10(val) {
return Math.log(val) / Math.LN10;
}
Math.LN10
is a built-in precomputed constant for Math.log(10)
, so this function is essentially identical to:
function log10(val) {
return Math.log(val) / Math.log(10);
}
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);
const logBase = (n, base) => Math.log(n) / Math.log(base);
https://en.wikipedia.org/wiki/Logarithm#Change_of_base
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);