Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning intermediate value to a variable makes the computation result complex

Python gives me a different result if I assign one of the intermediate steps to a variable, like this:

>>> -0.207 ** 0.66 - 1
-1.3536229379434348
>>> a = -0.207
>>> a ** 0.66 - 1
(-1.1703591496008927+0.30988214273656856j)

For this simple calculation, if I assign -0.207 to a temporary variable a, then the result of a ** 0.66 - 1 evaluates to a complex number.

Why does this happen, and how do I stop Python from doing that?

like image 738
kharsair Avatar asked Oct 12 '25 08:10

kharsair


1 Answers

The correct answer to your statement (according to python) is a negative number. -0.207**0.66-1 evaluates to about -1.35.
The reason this is happening is that you're miscalculating in the one-liner: -0.207 ** 0.66 - 1 actually evaluates to -(0.207 ** 0.66) - 1 and not to (-0.207) ** 0.66 - 1 like you'd expect.

When you separate the lines, you're changing the calculation to the second statement.

To stop this from happening, use explicit parentheses where there might be any ambiguity.

like image 131
Adid Avatar answered Oct 14 '25 23:10

Adid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!