[Numpy-discussion] reciprocal(0)
josef.pktd@gmai...
josef.pktd@gmai...
Sat Jun 6 23:22:34 CDT 2009
On Sat, Jun 6, 2009 at 11:49 PM, Ralf Gommers
<ralf.gommers@googlemail.com> wrote:
> 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[1] = np.nan
>>> x
array([0, 0])
>>> x[1]= 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[0]
array([0, 0])
Masked Arrays look good for this
>>> x = np.ma.array([0,1],dtype=int)
>>> x
masked_array(data = [0 1],
mask = False,
fill_value = 999999)
>>> x/x[0]
masked_array(data = [-- --],
mask = [ True True],
fill_value = 999999)
More information about the Numpy-discussion
mailing list