17

What should print (-2 ** 2) return? According to my calculations it should be 4, but interpreter returns -4.
Is this Python's thing or my math is that terrible?

4
  • You should do (-2)**2 instead May 20, 2014 at 11:58
  • 2
    The - has lower priority than **. This is interpreted as -(2**2), not (-2)**2...
    – l4mpi
    May 20, 2014 at 11:58
  • 2
    The main reason this confuses most people is that they expect -2 to be a literal meaning "negative 2", not an expression meaning "apply the negation operator to the literal 2 at runtime". Once you understand that it's an operator, the fact that it's a precedence issue is obvious; until you do, it's baffling. (That's why all the people who run into this are confused by -2 ** 2, not -x ** 2.)
    – abarnert
    Jul 31, 2014 at 17:46
  • in math -x² is a negative number or zero because power has higher precedence. So is -2² which is negative. Python is right
    – phuclv
    Feb 17, 2019 at 16:11

4 Answers 4

28

According to docs, ** has higher precedence than -, thus your code is equivalent to -(2 ** 2). To get the desired result you could put -2 into parentheses

>>> (-2) ** 2
4

or use built-in pow function

>>> pow(-2, 2)
4

or math.pow function (returning float value)

>>> import math
>>> math.pow(-2, 2)
4.0
0
6

The ** operation is done before the minus. To get the results expected, you should do

print ((-2) ** 2)

From the documentation:

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.

A full detail of operators precedence is also available in the documentation. You can see the last line is (expr) which force the expr to be evaluated before being used, hence the result of (-2) ** 2 = 4

1

you can also use math library...

math.pow(-2,2) --> 4
-math.pow(2,2) --> -4
math.pow(4,0.5) --> 2
0
-2

Python has a problem and does not see the -2 as a number. This seems to be by design as it is mentioned in the docs.

-2 is interpreted as -(2) {unary minus to positive number 2}

That usually doesn't give a problem but in -a ** 2 the ** has higher priority as - and so with - interpreted as a unary operatoe instead of part of the number -2 ** 2 evaluates to -2 instead of 2.

1
  • It's not Python's problem. This is how math works.
    – Asocia
    Jun 6, 2021 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.