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

Tim Hochberg tim.hochberg at ieee.org
Wed Oct 11 23:08:27 CDT 2006

```Greg Willden wrote:
> On 10/11/06, *Travis Oliphant* <oliphant at ee.byu.edu
> <mailto:oliphant at ee.byu.edu>> 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.
> 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; of course you don't
know *which* complex number it is unless you also specify the branch.
> Therefore Numpy *must* return a complex number.
No I don't think that it must. I've found it a very useful tool for the
past decade plus without it returning complex numbers from sqrt.
> Speed should not take precedence over correctness.
The current behavior is not incorrect.
>
> If Numpy doesn't return a complex number then it shouldn't pretend to
> support complex numbers.

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')

a = -numpy.arange(10)
with errstate(invalid='ignore'):
print numpy.sqrt(a) # This happily returns a bunch of NANs; and
one zero.
print numpy.sqrt(a.astype(complex)) # This returns a bunch of
complex values
print numpy.sqrt(a) # This raise a floating point error. No silent
NANs returned

This same error state make the vagaries of dividing by zero less
surprising as well.

-tim

-------------------------------------------------------------------------
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