Calculation error with pow operator

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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

Method 3

you can also use math library…

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

Method 4

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x