In Javascript,m the Math.log
method only returns the natural logarithm of the argument we pass in.
However, we may want to do calculations with logarithms of other bases.
In this article, we’ll look at ways to change the base of the logarithm calculation in JavaScript.
Use the Change of Base Formula
We can use the change of base formula to change the base of the logarithm.
To do this, we write:
const log10 = (val) => {
return Math.log(val) / Math.log(10);
}
console.log(log10(100))
We create the log10
function to compute the logarithm of a number with base 10.
In the function, we use the change of base rule by dividing the natural log of val
by the natural log of 10.
Therefore, the console log will log 2 since log with base 10 of 100 is 2.
We can make the function more versatile by making it accept the base of the log in addition to the value to take the log of.
For instance, we can write:
const log = (val, base) => {
return Math.log(val) / (base ? Math.log(base) : 1);
}
console.log(log(100, 10))
We create the log
function that takes the val
to take the log of and base
of the log.
And then we use the change of base rule by dividing the natural log of val
by the natural log of the base
if base
isn’t 0.
If base
is 0, we divide by 1.
Therefore, the console log will log 2 since we take the log of 100 with base 10.
Conclusion
We can apply the change of base rule to check the base of the logarithm with JavaScript.