[Numpy-discussion] Re: sqrt and divide

Robert Kern robert.kern at gmail.com
Tue Apr 11 23:16:03 CDT 2006

Stefan van der Walt wrote:
> Hi all
> Two quick questions regarding unintuitive numpy behaviour:
> Why is the square root of -1 not equal to the square root of -1+0j?
> In [5]: N.sqrt(-1.)
> Out[5]: nan
> In [6]: N.sqrt(-1.+0j)
> Out[6]: 1j

It is frequently the case that the argument being passed to sqrt() is expected
to be non-negative and all of their code strictly deals with numbers in the real
domain. If the argument happens to be negative, then it is a sign of a bug
earlier in the code or a floating point instability. Returning nan gives the
programmer the opportunity for sqrt() to complain loudly and expose bugs instead
of silently upcasting to a complex type. Programmers who *do* want to work in
the complex domain can easily perform the cast explicitly.

> Is there an easier way of dividing two scalars than using divide?
> In [9]: N.divide(1.,0)
> Out[9]: inf

x/y ?

> (also 
> In [8]: N.divide(1,0)
> Out[8]: 0
> should probably ruturn inf / nan?)

inf and nan are floating point values. The definition of int division used when
both arguments to divide() are ints also yields ints, not floats.

Robert Kern
robert.kern at gmail.com

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

More information about the Numpy-discussion mailing list