Search code examples
pythonoperator-precedence

In Python, why does a negative number raised to an even power remain negative?


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.


Solution

  • 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