38

I'm having a mental block here, and algebra not really being my thing, can you tell me how to re-write the JavaScript code below to derive the variable, c, in terms of a and b?:

a = Math.pow(b, c);
c = ?

Thanks!

Prem
  • 15,911
  • 11
  • 31
  • 35
  • 1
    Slightly related question: http://stackoverflow.com/questions/9309084/what-is-the-reverse-of-x-powy-5 – wip Feb 06 '14 at 03:52

2 Answers2

80
c = Math.log(a)/Math.log(b)
dusan
  • 9,104
  • 3
  • 35
  • 55
  • 4
    Might be worth mentioning that JavaScript is horrible at Math when dealing with precise numbers. var c = 3; var b = 10; var a = Math.pow(b,c) var d = Math.log(a)/Math.log(b); // d should equal 3 // d actually equals 2.9999999999999996 – tbh__ Mar 02 '17 at 21:14
  • 1
    @tbh__ is it safe to assume that if I'm working with integers and use Math.round() on the result it'll be accurate? Specifically I know my value is a power of 2, so `let power = Math.round( Math.log(value) / Math.log(2) );` should be accurate in my case? – Jake T. Mar 14 '18 at 21:04
  • 1
    Ahh, it appears for my specific case Math has me covered with Math.log2(num)! – Jake T. Mar 14 '18 at 21:13
  • how do you obtain b if you have a & c? – TatiOverflow Dec 06 '18 at 01:02
9

Logarithms. You want the logarithm of a. B is the base, c is the exponent, so

logb a = c

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263