Is there a short-hand for nth root of x in Python?
In maths, if I wish to calculate 3 to the power of 2 then no symbol is required, but I write the 2 small: 3²
. In Python this operation seems to be represented by the **
syntax.
>>> 3**2
9
If I want to go the other direction and calculate the 2nd root of 9 then in maths I need to use a symbol: 2√9 = 3
Is there a short-hand symbol in Python, similar to **
that achieves this i.e. 2<symbol>9
? Or do I need to use the math
module?
Solution 1:
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?
Solution 2:
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