Bizarre arithmetic results

Tim Chase python.list at tim.thechases.com
Thu Feb 11 07:47:56 EST 2010


Terrence Cole wrote:
> Can someone explain to me what python is doing here?
> 
> Python 3.1.1 (r311:74480, Feb  3 2010, 13:36:47) 
> [GCC 4.3.4] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> -0.1 ** 0.1
> -0.7943282347242815
>>>> a = -0.1; b = 0.1
>>>> a ** b
> (0.7554510437117542+0.2454609236416552j)
>>>> -abs(a ** b)
> -0.7943282347242815
> 
> Why does the literal version return the signed magnitude and the
> variable version return a complex?

I think this recently showed up on the list and the answer 
involved the order of operations and precedence of "-" vs. "**". 
  To check, try

   >>> (-0.1) ** 0.1
   >>> -(0.1 ** 0.1)

The first one is what the assignment-to-variables gains you, but 
I think "**" has a higher precedence than the unary-"-" so it 
gets performed first.

I don't have Py3 on my machine here, and 2.5 rejects the first form:

Python 2.5.4 (r254:67916, Nov 19 2009, 19:46:21) [GCC 4.3.4] on 
linux2
Type "help", "copyright", "credits" or "license" for more 
information.
 >>> -(0.1**0.1)
-0.79432823472428149
 >>> (-0.1)**0.1
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: negative number cannot be raised to a fractional power

But perhaps Py3 changes evaluation, returning an complex number.

-tkc






More information about the Python-list mailing list