[Numpy-discussion] Zero Division not handled correctly?
David Cournapeau
david@ar.media.kyoto-u.ac...
Mon Dec 7 00:18:52 CST 2009
Skipper Seabold wrote:
> I believe this is known, but I am surprised that division by "integer"
> zero results in the following.
>
> In [1]: import numpy as np
>
> In [2]: np.__version__
> Out[2]: '1.4.0.dev7539'
>
> In [3]: 0**-1 # or 0**-1/-1
> ---------------------------------------------------------------------------
> ZeroDivisionError Traceback (most recent call last)
>
> /home/skipper/school/Data/ascii/numpy/<ipython console> in <module>()
>
> ZeroDivisionError: 0.0 cannot be raised to a negative power
>
> In [4]: np.array([0.])**-1
> Out[4]: array([ Inf])
>
> In [5]: np.array([0.])**-1/-1
> Out[5]: array([-Inf])
>
> In [6]: np.array([0])**-1.
> Out[6]: array([ Inf])
>
> In [7]: np.array([0])**-1./-1
> Out[7]: array([-Inf])
>
> In [8]: np.array([0])**-1
> Out[8]: array([-9223372036854775808])
>
> In [9]: np.array([0])**-1/-1
> Floating point exception
np.array([0])**-1
This last one is sort of interesting - Skipper Seabold wrote:
> I believe this is known, but I am surprised that division by "integer"
> zero results in the following.
>
> In [1]: import numpy as np
>
> In [2]: np.__version__
> Out[2]: '1.4.0.dev7539'
>
> In [3]: 0**-1 # or 0**-1/-1
> ---------------------------------------------------------------------------
> ZeroDivisionError Traceback (most recent call last)
>
> /home/skipper/school/Data/ascii/numpy/<ipython console> in <module>()
>
> ZeroDivisionError: 0.0 cannot be raised to a negative power
>
> In [4]: np.array([0.])**-1
> Out[4]: array([ Inf])
>
> In [5]: np.array([0.])**-1/-1
> Out[5]: array([-Inf])
>
> In [6]: np.array([0])**-1.
> Out[6]: array([ Inf])
>
> In [7]: np.array([0])**-1./-1
> Out[7]: array([-Inf])
>
> In [8]: np.array([0])**-1
> Out[8]: array([-9223372036854775808])
>
> In [9]: np.array([0])**-1/-1
> Floating point exception
This last one is sort of interesting - np.array([0])**-1 returns the
smallest long, and on 2-complement machines, this means that its
opposite is not representable. IOW, it is not a divide by zero, but a
division overflow, which also generates a SIGFPE on x86. I think the
crash is the same as the one on this simple C program:
#include <stdio.h>
int main(void)
{
long a = -2147483648;
long b = -1;
printf("%ld\n", a);
a /= b;
printf("%ld\n", a);
return 0;
}
I am not sure about how to fix this: one simple way would be to detect
this case in the LONG_divide ufunc (and other concerned signed integer
types). Another, maybe better solution is to handle the signal, but
that's maybe much more work (I still don't know well how signals
interact with python interpreter).
cheers,
David
More information about the NumPy-Discussion
mailing list