Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 698
RolfBly Avatar asked Dec 31 '14 21:12

RolfBly


1 Answers

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

like image 56
Amber Avatar answered Oct 24 '22 12:10

Amber