在 Python 中,为什么负数的偶次幂仍然是负数? [英] In Python, why does a negative number raised to an even power remain negative?
问题描述
在 Python 中
<预><代码>>>>我 = 3>>>-i**4-81为什么 -i**4
不计算为 (-i)**4
,而是计算为 -(i**4)
?
我想有人可能会争辩说,提升到幂优先于 i
与减一的(隐式)乘法(即你应该阅读 -1*i**4
).但是在我学习数学的地方,-i**n
与 n
偶数和 i
正数,应该是正数.
**
运算符比 Python 中的 -
运算符绑定得更紧密.如果你想覆盖它,你可以使用括号,例如(-i)**4
.
https://docs.python.org/2/reference/表达式.html#operator-precedencehttps://docs.python.org/3/reference/expressions.html#operator-precedence
In Python
>>> i = 3
>>> -i**4
-81
Why is -i**4
not evaluated as (-i)**4
, but as -(i**4)
?
I suppose one could argue that raising to a power takes precedence over (implicit) multiplication of i
with minus one (i.e. you should read -1*i**4
).
But where I learned math, -i**n
with n
even and i
positive, should come out positive.
The **
operator binds more tightly than the -
operator does in Python. If you want to override that, you'd use parentheses, e.g. (-i)**4
.
https://docs.python.org/2/reference/expressions.html#operator-precedence https://docs.python.org/3/reference/expressions.html#operator-precedence
这篇关于在 Python 中,为什么负数的偶次幂仍然是负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!