views:

175

answers:

2

Hi there, I was wondering how can I get the inverse of power in ruby?

2 ** 4 => 16

and then I would like to get the inverse of it, and I'm not sure which operator to use :(

16 ?? 2 => 4

Thanks a lot

+2  A: 
Math.log(16) / Math.log(2)
Peter
+12  A: 

The inverse of exponentiation is the logarithm.

If ab= c, then logac = b.

You can find logarithm in the Math module. This is logarithm base-e (log) or base-10 (log10). To get a logarithm to base-N, use the formula:

         log a
            x
log a = -------
   N     log N
            x

where x is a value such as e or 10. For your specific case:

              log 16
                 e
log 16   =   -------   =   Math.log(16) / Math.log(2)
   2          log 2
                 e

Whether you consider the explanation good (because it expands your knowledge) or bad (because you hated high school math) is up to you :-)

paxdiablo
Ha, thanks a lot paxdiablo this was a very good explanation, and yes you're right I used to hate it, but now I can see that I've missed a lot because of that, cheers!
ludicco