質問

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?

役に立ちましたか?

解決

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

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

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)

Basically sqrt(9) is equivalent to 9^.5

>>>9**.5
3.0

You should do

16**(0.5) #If you print it, you get 4, So you can use this formula.
def nthrootofm(a,n):
    return pow(a,(1/n))
a=81
n=4
q=nthrootofm(a,n)
print(q)

pow() function takes two parameters .

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top