lontivero lontivero - 2 months ago 13
Python Question

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)

Answer Source

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