在Python中是否存在x的第n个根的简写

why*_*heq 25 python math operators

简单的语法问题.

在数学中,如果我有两个数字3和2,我希望计算3到2的幂,那么不需要符号,但我写了两个小.在Python这个操作中似乎用**语法表示.

>>> 3**2
9
Run Code Online (Sandbox Code Playgroud)

如果我想转向另一个方向并计算9的第2根,那么在数学中我需要使用符号:

x的第n个根

在Python中是否有一个简写符号,类似于**实现这一点即2<symbol>9.或者我需要使用该math模块吗?

Har*_*non 44

n的根xx^(1/n),所以你可以9**(1/2.0)找到9的第二根,例如.通常,您可以将x的第n个根计算为:

x**(1/float(n))
Run Code Online (Sandbox Code Playgroud)

你也可以1.0/n代替1/float(n).这是必需的,结果是一个float而不是一个int.

  • 在Python 3中,没有必要将结果强制转换为浮点数,它将自动发生. (7认同)

Nac*_*eme 6

另外:x**(n**-1),相同但比x**(1/float(n))


ely*_*ely 5

如果您更喜欢按功能应用此运算而不是使用中缀运算符(符号**),则可以将底数和指数作为参数传递给函数pow

In [23]: (9**(0.5)) == pow(9, 0.5)
Out[23]: True
Run Code Online (Sandbox Code Playgroud)

我也喜欢在 Python 中寻找 Infix hack的新用途,尽管它比重型解决方案更有趣。但您可以通过执行以下操作来有效地为此制作自己的个人符号:

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
Run Code Online (Sandbox Code Playgroud)


小智 5

您还可以使用一些对数:

x 的第 N 个根:

 exp(log(x)/n)
Run Code Online (Sandbox Code Playgroud)