2

I saw this post recently, about getting square roots in python: How to calc square root in python?

I have used the sqrt(x) command, but I don't know how to make it work for cube roots and anything higher than that.

Also, I'm using Python 3.5.2.

Any help on this?

Community
  • 1
  • 1
MasterHolbytla
  • 177
  • 1
  • 2
  • 11

1 Answers1

5

In Python, you may find floating cube root by:

>>> def get_cube_root(num):
...     return num ** (1. / 3)
... 
>>> get_cube_root(27)
3.0

In case you want more generic approach to find nth root, you may use below code which is based on Newton's method:

# NOTE: You may use this function only for integer numbers
# k is num, n is the 'n' in nth root
def iroot(k, n):
    u, s = n, n+1
    while u < s:
        s = u
        t = (k-1) * s + n // pow(s, k-1)
        u = t // k
    return s
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • 2
    It would be interesting to see in what cases your `iroot` is better than `k ** (1./n)`. – Qwertiy Mar 31 '17 at 11:31
  • 1
    @Qwertiy Indeed... And the function as provided returns wrong results (in both 2.7 and 3.5, using `//` or `/` division). – Theo d'Or Oct 20 '18 at 22:13