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?
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().
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.
In Mathematics, the nth root of a number x is a number y which when raised to the power n, obtains x: yn=x.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With