Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the reverse of Math Power (**) in Ruby?

Tags:

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 
like image 337
zanona Avatar asked Jul 20 '10 01:07

zanona


2 Answers

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 :-)

like image 200
paxdiablo Avatar answered Oct 19 '22 00:10

paxdiablo


Math.log(16) / Math.log(2) 
like image 30
Peter Avatar answered Oct 18 '22 22:10

Peter