Search code examples
pythonvariablesfloating-pointexponentnegative-integer

Why do I get different results when I use either values or variables when coding an exponentiation?


The following code gives different output and I can't tell why. I have basic programming knowledge so forgive me if its obvious.

Num = -0.8

Print(-0.8**-0.8)

Print(Num**Num) 

Output:

-1.1954406247375462

(-0.967131781178879-0.7026623692120304j)

Why does the second output give an imaginary number as the output? I basically want the first output but using variables instead of the actual number.

I tried print(-(Num)**Num)) because I thought it was an operator precedence issue but it was still the same result. The difference in output is only apparent with negative floats by the way.


Solution

  • ** has higher precedence than unary -. So -0.8**-0.8 is - (0.8**-0.8), which represents −(0.8−0.8), about −1.1954406247375462.

    (-0.8)**-0.8 gives the same result as the Num**Num expression, (-0.967131781178879-0.7026623692120304j).

    I basically want the first output but using variables instead of the actual number.

    That is not going to work with Num**Num given your assignment of −0.8 to Num. −1.1954406247375462 is not a correct result for that exponentiation. If instead you assign 0.8 to Num, you could use - Num**-Num.