[Numpy-discussion] reciprocal(0)

josef.pktd at gmail.com josef.pktd at gmail.com
Sun Jun 7 00:22:34 EDT 2009

On Sat, Jun 6, 2009 at 11:49 PM, Ralf Gommers
> Hi,
>
> I expect `reciprocal(x)` to calculate 1/x, and for input 0 to either follow
> the python rules or give the np.divide(1, 0) result. However the result
> returned (with numpy trunk) is:
>
>>>> np.reciprocal(0)
> -2147483648
>
>>>> np.divide(1, 0)
> 0
>>>> 1/0
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> ZeroDivisionError: integer division or modulo by zero
>
> The result for a zero float argument is inf as expected. I want to document
> the correct behavior for integers, what should it be?
>
> Cheers,
> Ralf

Add a warning not to use integers, if a nan or inf is possible in the
code, because the behavior in numpy is not very predictable.
overflow looks ok, but I really don't like the casting of nans to zero.

Josef

>>> x = np.array([0,1],dtype=int)

>>> x = np.nan
>>> x
array([0, 0])

>>> x= np.inf
Traceback (most recent call last):
OverflowError: cannot convert float infinity to long

>>> np.array([np.nan, 1],dtype=int)
array([0, 1])

>>> np.array([0, np.inf],dtype=int)
Traceback (most recent call last):
ValueError: setting an array element with a sequence.

>>> np.array([np.nan, np.inf]).astype(int)
array([-2147483648, -2147483648])

and now yours looks like an inf cast to zero

>>> x = np.array([0,1],dtype=int)
>>> x/x
array([0, 0])

Masked Arrays look good for this

>>> x = np.ma.array([0,1],dtype=int)
>>> x