25

I was wondering how to 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
1
  • To get simple square root, just use Ruby's Math.sqrt(16) # => 4.0 - you get a float because a square root is not always an integer. If you definitely want/expect an integer, cast the result to an int with Math.sqrt(16).to_i. which will round the result down to the nearest integer. Feb 4, 2021 at 15:07

3 Answers 3

67

The inverse of exponentiation is the logarithm. If ab = c, then logac = b.

You can find logarithm functions in the Math module, specifically log() for base-e and log10() for base-10.

To get a logarithm to a different base (say n), use the formula logNa = logxa/logxN, where x is a value such as e or 10.

For your specific case:

log216
= loge16/loge2
= Math.log(16) / Math.log(2)
= 4

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

1
  • 4
    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!
    – zanona
    Jul 20, 2010 at 2:24
6
Math.log(16) / Math.log(2)
1

A cleaner way to obtain the logarithm, starting with Ruby 1.9.1, would be to use Math.log2:

[1] pry(main)> Math.log2(2**4)
=> 4.0

Your Answer

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

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