python中的'Power of'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34603595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'Power of' in python
提问by
Why is it when:
为什么是这样:
>> b = -1
>> b**2
1
But:
但:
>> -1**2
-1
If i import the math library, it's no problem.
如果我导入数学库,那就没问题了。
>> from math import pow
>> pow(b,2)
1.0
>> pow(-1,2)
1.0
采纳答案by astrosyam
From the Python documentation: https://docs.python.org/3/reference/expressions.html#the-power-operator
来自 Python 文档:https: //docs.python.org/3/reference/expressions.html#the-power-operator
The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right.
Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands):
-1**2
results in-1
.
幂运算符比左边的一元运算符绑定得更紧密;它的绑定不如右侧的一元运算符紧密。
因此,在无括号的幂和一元运算符序列中,运算符从右到左求值(这不限制操作数的求值顺序):
-1**2
结果为-1
。
回答by Vikram Tiwari
Since its working on 1 not -1 as a whole. This will give expected result.
因为它在 1 上工作而不是 -1 作为一个整体。这将给出预期的结果。
(-1)**2
回答by doptimusprime
It is related with operator precedence.
它与运算符优先级有关。
Try
尝试
(-1)**2
**
is being evaluated first and then -
. Hence, you got -1
.
**
正在首先评估,然后-
。因此,你得到了-1
.
In case of pow
function, -1
is being evaluated first.
在pow
函数的情况下,-1
首先被评估。
See reference on https://docs.python.org/2/reference/expressions.html#the-power-operator
请参阅https://docs.python.org/2/reference/expressions.html#the-power-operator 上的参考