简体   繁体   中英

Why does `-(num)**(even_number)` give `-(num^(even_number))` as result?

This is something weird I noticed.

Any particular reason why -5**2 gives -25 and math.pow(-5,2) gives 25? The answer should be 25. So what is the reason for the -25 answer?

>>> -5**2
-25
>>> -5**4
-625
>>> 5**2
25
>>> 5**4
625
>>> import math
>>> pow(-5,2)
25
>>> pow(-5,4)
625
>>>

In Python the ** operator has higher precedence than the - operator, so in your expression 5 ** 2 is evaluated first, then negated. You can apply negation first by using brackets:

>>> -5**2
-25
>>> (-5)**2
25

This is all explained in the documentation

The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right.

Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): -1**2 results in -1.

The documentation for math.pow specifies that it raises x to the power of y .

So, math.pow calculates (-5)**4 . whereas just writing -5**4 is equivalent to -1 * 5 **4 , since by operator precedence in Python the unary operator - has less precedence than the power operator ** .

This is because of the operator precedence in python.

If we look at the operator precedence , we see that the unary operator -x has lower precedence than the power operator x**y , so that the expression -5**2 means to first apply the square to the 5 and then apply the negative sign to the result. This first operation gives 25, which then gives -25.

The expression math.pow(-5,2) means to square the -5. This is equivalent to (-5)**2 .

It's because of that the precedence of - operator is lower than power operator ** . In fact your expression will be calculated as following:

>>> -(5 ** 2)

Try the following to get the correct result:

>>> (-5) ** 2
25

For more information you can read the python Operator precedence :

The following table summarizes the operator precedence in Python, from lowest precedence (least binding) to highest precedence (most binding).

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM