Should numpy.sqrt(-1) return 1j rather than nan?

Charles R Harris charlesr.harris at
Wed Oct 11 23:49:45 CDT 2006

On 10/11/06, Tim Hochberg <tim.hochberg at> wrote:
> Greg Willden wrote:
> > On 10/11/06, *Travis Oliphant* <oliphant at
> > <mailto:oliphant at>> wrote:
> >
> >     Stefan van der Walt wrote:
> >     >Further, if I understand correctly, changing sqrt and power to give
> >     >the right answer by default will slow things down somewhat.  But
> >     is it
> >     >worth sacrificing intuitive usage for speed?
> >     >
> >     For NumPy, yes.
> >
> >     This is one reason that NumPy by itself is not a MATLAB replacement.
> >
> >
> > This is not about being a Matlab replacement.
> > This is about correctness.
> > Numpy purports to handle complex numbers.
> > Mathematically, sqrt(-1) is a complex number.
> That's vastly oversimplified. If you are working with the reals, then
> sqrt(-1) is undefined (AKA nan). If you are working in the complex
> plane, then sqrt(-1) is indeed *a* complex number;

And if you are working over the rationals, sqrt(-1) and sqrt(-2) lead to
different field extensions ;) Of course, numpy doesn't *have* rationals, so
I'm just being cute.


Personally I think that the default error mode should be tightened up.
> Then people would only see these sort of things if they really care
> about them. Using Python 2.5 and the errstate class I posted earlier:
>     # This is what I like for the default error state
>     numpy.seterr(invalid='raise', divide='raise', over='raise',
>     under='ignore')

I like these choices too. Overflow, division by zero, and sqrt(-x) are
usually errors, indicating bad data or programming bugs. Underflowed floats,
OTOH, are just really, really small numbers and can be treated as zero. An
exception might be if the result is used in division and no error is raised,
resulting in a loss of accuracy.

If complex results are *expected*, then this should be made explicit by
using complex numbers. Numpy allows finegrained control of data types and
array ordering, it is a bit closer to the metal than Matlab. This extra
control allows greater efficiency, both in speed and in storage, at the cost
of a bit more care on the programmers side.

-------------- next part --------------
An HTML attachment was scrubbed...
-------------- next part --------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
-------------- next part --------------
Numpy-discussion mailing list
Numpy-discussion at

More information about the Numpy-discussion mailing list