RobMcC
RobMcC

Reputation: 412

Inconsistent fractional exponents in python

Please could anyone explain in the below example why the one gets a different answer if depending on whether the number being raised is input directly vs input as a variable?:

>>>print(-2**(1/0.33))
-8.169812850522913

>>>x=-2
>>>print(x**(1/0.33))
(-8.132819305372337-0.7765900841063754j)

Inn addition I'd be very grateful if anyone could explain how to get the first answer but using the second approach

Upvotes: 2

Views: 247

Answers (2)

yatu
yatu

Reputation: 88236

Because of operator precedence (** has a higher precedence than the unary -), your first expression is being evaluated as:

-(2**(1/0.33))
# -8.169812850522913

Whereas in the second case, since you've already defined -2 as a variable, it is evaluated as:

(-2)**(1/0.33)
# (-8.132819305372337-0.7765900841063753j)

Which happens to result in a complex number.

Upvotes: 2

Metapod
Metapod

Reputation: 416

The first case, only the 2 has the exponent, the second case it's '-2'. (-2)**(1/0.33) should give the second result

Upvotes: 1

Related Questions