[Tutor] Little problem with math module

joe gallo gallo.j at gmail.com
Mon Apr 21 10:04:48 CEST 2008


On Mon, Apr 21, 2008 at 12:07 AM, Alan Gauld <alan.gauld at btinternet.com>
wrote:

>
> >>> pow(20, 0.3333333)
> 2.7144173455393048
> >>> pow(-20, 0.3333333)
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> ValueError: negative number cannot be raised to a fractional power
> >>> -20**0.3333333
> -2.7144173455393048
> >>>
>
> So the exponentiation operator seems happy but pow isn't.
>
> Very strange and potentially a bug in pow()?
> Unless someone knows a reason for it?



I think you're confusing the order of operations.

math.pow(-20, (1.0/3.0)) and -20**(1.0/3.0) are not equivalent

Whereas, as john mentioned, -20**(1.0/3.0) is actually -(20**(1.0/3.0)),
math.pow(-20, (1.0/3.0)) is (-20)**(1.0/3.0)

The behavior of ** is appropriate since
http://docs.python.org/ref/summary.html shows that exponentiation has higher
precedence over positive, negative.

Also, I found this from http://www.python.org/download/releases/2.0/:

*Raise ZeroDivisionError when raising zero to a negative number, e.g. 0.0 **
> -2.0. Note that math.pow is unrelated to the builtin power operator and the
> result of math.pow(0.0, -2.0) will vary by platform. On Linux, it raises a
> ValueError.*


which is related to why some people would get nan and others a ValueError.

And, just to clarify (although i doubt there was any confusion over it),
-20**(1/3) = -1 * (20**0) = -1 due to integer division magic.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080421/1547f449/attachment.htm 


More information about the Tutor mailing list