Different results for same mathematical operations

Viewed 62

I encountered a strange behaviour in simple Python operations. It happens with power operation with two specific numbers:

print(-0.5660330877786267 ** 0.5515471713326932)
a = -0.5660330877786267
b = 0.5515471713326932
print(a ** b)

The outputs are unexpectingly not the same:

-0.7306015753489663
(-0.117797331106763+0.7210426136411876j)

Dose someone have an idea why this happens?

This happens with Python 3.8.1 on Windows. I tried both ** operator and pow function.

enter image description here

2 Answers

This is because

print(-0.5660330877786267 ** 0.5515471713326932)

is actually

print(-(0.5660330877786267 ** 0.5515471713326932))

You can learn about operator precedence in the documentation

-0.5660330877786267 ** 0.5515471713326932 is not equivalent to (-0.5660330877786267) ** (0.5515471713326932). Because of the relevant precedence rules, it is equivalent to -(0.5660330877786267 ** 0.5515471713326932), which of course has a different result.

With the pow function call, of course, the arguments are necessarily evaluated before the function is called, so it doesn't matter whether the values come from variables or literals.

Related