Zerium
Zerium

Reputation: 17333

How to find the logarithm of two numbers in JavaScript?

Basically like the opposite of Math.pow().

I want a function which can be used as such a logarithm:

var mynum = findpower(36, 6); // 2, because 6 squared is 36

How could such a function be constructed?

Upvotes: 0

Views: 1390

Answers (1)

Artem Sobolev
Artem Sobolev

Reputation: 6069

It's a logarithm

Math.log(36) / Math.log(6) = 2

in general case

Math.log(number) / Math.log(base)

The logarithm has following property: if a = log(n = number, b = base) (usually denoted as logb(n)) then ba = n. In my code above I used logarithms property: logy(x) = logc(x) / logc(y) where c is any positive number.

Math.log in examples above is the natural logarithm, i.e. the logarithm with base = e (≈ 2.718281828…, see Math.E). Obviously, if we have the natural logarithm (usually denoted as ln(n) or log(n)), then we have the logarithm with any other base via the equation given above: logy(x) = log(x) / log(y)

Upvotes: 9

Related Questions