5.19. Finding Cube Roots, Fourth Roots, and so on

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 ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.