[Tutor] Little problem with math module

John Fouhy john at fouhy.net
Mon Apr 21 04:40:57 CEST 2008


On 21/04/2008, Tiago Katcipis <katcipis at inf.ufsc.br> wrote:
> im not understanding why is this a problem...i have this simple function
>
>  def newton_divergente(x):
>   return math.pow(x, 1.0/3.0)
>
>  but when x = -20 it returns this error
>
>  return math.pow(x, 1.0/3.0)
>  ValueError: math domain error
>
>  but why is that? is it impossible to calculate -20 ^ (1/3) ?
>
>  here on my calculator i get the result -6,666666667, but python seens to
>  dont now the answer, why? am i doing something wrong? =/

-6.66.. looks more like -20 * (1.0/3.0), rather than -20 ** (1.0/3.0).

That said, it's an interesting error.  It must be an artefact of the
method python uses to calculate roots, but I don't know what this
error is.  This is also interesting:

>>> math.pow(-20, 1.0/3.0)
nan
>>> -20 ** (1.0/3.0)
-2.7144176165949063

(nan stands for "not a number")

And, one more for good luck:

>>> -1 ** (1.0/2.0)
-1.0

Hmm, that's not quite right!  Python supports a complex datatype, but
evidently the math.* functions don't extend to producing complex
outputs when necessary.  At a guess, the algorithm for calculating
math.pow(x,y) says something like "If x is negative there might not be
a real solution, so we won't try to find it".  Whereas the algorithm
for x**y just plows ahead -- and if the input is bad, the output might
be too (GIGO).

If you're going to be working with complex numbers, you might be
better off looking at scipy or some other module that provides more
mathematical grunt.

-- 
John.


More information about the Tutor mailing list