Simple syntax question.
In maths if I have two number 3 and 2 and I wish to calculate 3 to the power of 2 then no symbol is required but I write the two small. In
nth root of x
is x^(1/n)
, so you can do 9**(1/2.0)
to find the 2nd root of 9, for example. In general, you can compute the nth root of x as:
x**(1/float(n))
You can also do 1.0/n
instead of 1/float(n)
. It is required so that the result is a float
rather than an int
.
Also: x**(n**-1)
, which is the same but shorter than x**(1/float(n))
If you prefer to apply this operation functionally rather than with an infix operator (the **
symbol), you can pass the base and exponent as arguments to the pow
function:
In [23]: (9**(0.5)) == pow(9, 0.5)
Out[23]: True
I am also fond of finding new uses for this Infix hack in Python although it's more of a fun aside than a heavy-duty solution. But you could effectively make your own personal symbol for this by doing the following:
class Infix:
def __init__(self, function):
self.function = function
def __ror__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __or__(self, other):
return self.function(other)
def __rlshift__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __rshift__(self, other):
return self.function(other)
def __call__(self, value1, value2):
return self.function(value1, value2)
root_of = Infix(lambda x,y: y**(1.0/x))
print 2 |root_of| 9
3.0
def nthrootofm(a,n):
return pow(a,(1/n))
a=81
n=4
q=nthrootofm(a,n)
print(q)
pow() function takes two parameters .
You may also use some logarithms:
Nth root of:
X = exp(log(n)/x)
There is. It's just **
=)
Any nth root is an exponentiation by 1/n
, so to get the square root of 9, you use 9**(1/2)
(or 9**0.5
) to get the cube root, you use 9 ** (1/3)
(which we can't write with a simpler fraction), and to get the nth root, 9 ** (1/n)
.
Also note that as of Python 3, adding periods to integers to make them a float is no longer necessary. Saying 1/3
works the way you would actually expect it to, giving 0.333...
as result, rather than zero. For legacy versions of Python, you'll have to remember to use that period (but also critically wonder why you're using a legacy version of a programming language)