Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is -2**2 == -4 but math.pow(-2, 2) == 4.0?

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)

like image 685
lontivero Avatar asked Aug 28 '17 01:08

lontivero


2 Answers

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

like image 192
Reblochon Masque Avatar answered Sep 28 '22 16:09

Reblochon Masque


You can check the precedence from the Python3 documentation.

-2**2

calculates as : -(2**2) = -4.

like image 33
ABcDexter Avatar answered Sep 28 '22 16:09

ABcDexter