October 2006
Intermediate to advanced
888 pages
16h 55m
English
Ruby has a built-in square root function (Math.sqrt) because that function is so commonly used. But what if you need higher level roots? If you remember your math, this is easy.
One way is to use logarithms. Recall that e to the x is the inverse of the natural log of x, and that when we multiply numbers, that is equivalent to adding their logarithms.
x = 531441 cuberoot = Math.exp(Math.log(x)/3.0) # 81.0 fourthroot = Math.exp(Math.log(x)/4.0) # 27.0
However, it is just as easy and perhaps clearer simply to use fractions with an exponentiation operator (which can take any integer or floating point value).
include Math y = 4096 cuberoot = y**(1.0/3.0) # 16.0 fourthroot = y**(1.0/4.0) # 8.0 fourthroot ...
Read now
Unlock full access