Reputation: 5275
Why are not these two statements equivalents?
>> math.pow(-2,2)
4.0
>> -2 ** 2
-4
Python 3.5.3 (default, Jan 19 2017, 14:11:04)
Upvotes: 6
Views: 299
Reputation: 376
because the precedence of '-' is behind the precedence of '**', use (-2)**2 to calculate -2 at first
Upvotes: 1
Reputation: 2941
You can check the precedence from the Python3 documentation.
-2**2
calculates as : -(2**2)
= -4
.
Upvotes: 1
Reputation: 36742
The order of execution of the operators (operator precedence) matters here: with -2**2
, the exponentiation of 2 to the power 2 is first executed, then the negative sign.
Use parenthesis to obtain the desired result
(-2)**2 = 4
Upvotes: 7