Mayank Choudhary - 11 months ago 43

Python Question

This is something weird I noticed.

Any particular reason why -5**2 gives -25 and math.pow(-5,2) gives 25? The answer should be 25. So what is the reason for the -25 answer?

`>>> -5**2`

-25

>>> -5**4

-625

>>> 5**2

25

>>> 5**4

625

>>> import math

>>> pow(-5,2)

25

>>> pow(-5,4)

625

>>>

Answer

The documentation for `math.pow`

specifies that it raises `x`

to the power of `y`

.

So, `math.pow`

calculates `(-5)**4`

. whereas just writing `-5**4`

is equivalent to `-1 * 5 **4`

, since by operator precedence in Python the unary operator `-`

has less precedence than the power operator `**`

.