Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 721
whytheq Avatar asked Oct 08 '13 18:10

whytheq


People also ask

How do you find the nth root of x in Python?

For example, if we want to find the square root of a number in Python, we pass “1/3” to the pow() function. In general, to find the nth root of a number in Python, pass “1/n”. For example, to get the fifth root of a number, we pass “1/5” to the second parameter of pow().

How do you write the root of x in Python?

sqrt() function is an inbuilt function in Python programming language that returns the square root of any number. Syntax: math. sqrt(x) Parameter: x is any number such that x>=0 Returns: It returns the square root of the number passed in the parameter.

What is the nth root of x?

In Mathematics, the nth root of a number x is a number y which when raised to the power n, obtains x: yn=x.


2 Answers

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?

like image 151
Hari Menon Avatar answered Oct 19 '22 19:10

Hari Menon


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
like image 10
Idvar Avatar answered Oct 19 '22 18:10

Idvar