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!

1

2 Answers 2

80
c = Math.log(a)/Math.log(b)
4
  • 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 2, 2017 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, 2018 at 21:04
  • 1
    Ahh, it appears for my specific case Math has me covered with Math.log2(num)!
    – Jake T.
    Mar 14, 2018 at 21:13
  • how do you obtain b if you have a & c? Dec 6, 2018 at 1:02
9

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

logb a = c

1
  • 1
    Seems true, but this is not JavaScript, only pure math.
    – CLS
    Sep 5, 2022 at 9:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.