Why am I getting different answers when I convert a string to a float, vs just using the float value from the start

69 views Asked by At

I am trying to convert 2 strings to floats, then raise one to the power of the other. For some reason the output of float('x') ** float('y') vs x ** y are sometimes not the same

For example:

float('-5') ** float('-5') 
0.00032

vs

-5 ** -5
0.00032

this is working fine; however, some numbers do not. For example:

float('-5.04') ** float('-5.04')
-0.00028596440705202706+3.612570580059258e-05j

vs:

-5.04 ** -5.04
-0.0002882372438117746

(this bottom one is the correct answer btw)

Any suggestions as to why this is happening?

1

There are 1 answers

0
luk2302 On

-5.04 ** -5.04 is evaluated as -(5.04 ** -5.04) because ** has higher operator precedence than the unary -. You can see that by comparing the results:

>>> 5.04 ** -5.04
0.0002882372438117746
>>> -5.04 ** -5.04
-0.0002882372438117746
>>> -(5.04 ** -5.04)
-0.0002882372438117746

To "fix" this you would need to add parenthesis around the first number with its unary -:

>>> (-5.04) ** -5.04
(-0.0002859644070520271+3.6125705800592075e-05j)