math – Is there a short-hand for nth root of x in Python?

math – Is there a short-hand for nth root of x in Python?

nth root of x is x^(1/n), so you can do 9**(1/2) to find the 2nd root of 9, for example. In general, you can compute the nth root of x as:

x**(1/n)

Note: In Python 2, you had to do 1/float(n) or 1.0/n so that the result would be a float rather than an int. For more details, see Why does Python give the wrong answer for square root?

You may also use some logarithms:

Nth root of x:

exp(log(x)/n)

For example:

>>> from math import exp, log
>>> x = 8
>>> n = 3
>>> exp(log(x)/n)
2.0

math – Is there a short-hand for nth root of x in Python?

Also: x**(n**-1), which is the same but shorter than x**(1/float(n))

Leave a Reply

Your email address will not be published. Required fields are marked *