math.nroot [was Re: A brief question.]

Steven D'Aprano steve at REMOVETHIScyber.com.au
Mon Jul 4 19:13:24 EDT 2005


On Mon, 04 Jul 2005 15:35:56 +0100, Tom Anderson wrote:

>>> Also, would it be a good idea for (-1.0) ** 0.5 to evaluate to 1.0j? It
>>> seems a shame to have complex numbers in the language and then miss this
>>> opportunity to use them!
>>
>> It's generally true in Python that complex numbers are output only if 
>> complex numbers are input or you explicitly use a function from the 
>> cmath module. [...] The presumption is that a complex result is more 
>> likely the result of program error than intent for most applications. 
>> The relative handful of programmers who expect complex results can get 
>> them easily, though.
> 
> A reasonable presumption.
> 
> I always got really wound up that the calculator i had at school had this 
> behaviour too, *even in complex number mode*! Come to think of it, i don't 
> think it could do roots of imaginary numbers at all. However, python is 
> not a calculator.

Of course it is :-)

py> 1+2
3

It even works with complex numbers:

py> print (-1+0j)**0.5
(6.12303176911e-17+1j)

although you have to watch out for those rounding errors in floating 
point.

py> import cmath
py> cmath.sqrt(-1)
1j

-- 
Steven




More information about the Python-list mailing list