3

I want to use dynamic base for logarithm in JavaScript.

ex: logarithm number 16 and base 5 then output should be 1.722706232

How to archive this using JavaScript?

I know how to archive this for base 10. Here is the code for number 16 and base 10

console.log(Math.log10(16));
Bharata
  • 13,509
  • 6
  • 36
  • 50
Ketan Modi
  • 1,780
  • 1
  • 16
  • 28

3 Answers3

4

Use Math.log(), Divide the logarithm of the number with the logarithm of the desired base.

console.log(Math.log(16)/Math.log(5));
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

logn(x) = loge(x) / loge(n)

so

function generalLog(n, x) {
   return Math.log(x) / Math.log(n);
}
Pointy
  • 405,095
  • 59
  • 585
  • 614
0

You can use simple mathematics to do this:

 log_y (x) = log_10 (x) / log_10 (y) 
Bharata
  • 13,509
  • 6
  • 36
  • 50