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

In python

>>> i = 3 >>> -i**4 -81 

Why is -i**4 not evaluated as (-i)**4 , but how -(i**4) ?

I suppose it can be argued that raising to a degree takes precedence over (implicit) multiplication of i with minus one (i.e. you should read -1*i**4 ). But where I studied math, -i**n with n even and i positive should turn out to be positive.

+6
source share
4 answers

The ** operator binds more strongly than the operator - does in Python. If you want to override this, you should use parentheses, for example. (-i)**4 .

https://docs.python.org/2/reference/expressions.html#operator-precedence https://docs.python.org/3/reference/expressions.html#operator-precedence

+9
source

The power operator ( ** ) has a higher priority than the unary negation operator ( - ). -i**4 is evaluated as -(i**4) - i.e. you take 3 to power four, which is 81, and then deny it, resulting in -81 .

+2
source

You can use the pow () function from math.

 import math i = 3 math.pow(-i,4) 

This will give a positive value.

As stated here: Exponents in python x. ** y vs math.pow (x, y) , this option (or just build in pow ()) would be ideal if you want to always create a float.

+2
source

You need to do (-i) ** 4 to get a positive result.

They have a higher priority than '-'.

If in doubt, use parentheses. (or, as Amber suggested, refer to the language documentation)

0
source

Source: https://habr.com/ru/post/980384/


All Articles