问题
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.
回答1:
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
回答2:
The power operator (**
) has a higher precedence than the unary negation (-
) operator. -i**4
is evaluated as -(i**4)
- i.e., you take 3 up to the power of four, which is 81, and then negate it, resulting in -81
.
回答3:
You can use the pow() function from math.
import math
i = 3
math.pow(-i,4)
This will yield a positive value.
As stated here: Exponentials in python x.**y vs math.pow(x, y), this option (or just build in pow()) would be ideal if you want to always produce a float.
回答4:
You have to do (-i)**4 to get a positive result.
The *'s have higher priority than the '-'.
When in doubt, use parentheses. (or, as Amber suggested, refer to the language documentation)
来源:https://stackoverflow.com/questions/27726592/in-python-why-does-a-negative-number-raised-to-an-even-power-remain-negative