[Numpy-discussion] somewhat less stupid problem with 0-d arrays

Sebastian Berg sebastian at sipsolutions.net
Sat May 11 09:17:18 EDT 2013


On Sat, 2013-05-11 at 08:30 -0400, Neal Becker wrote:
> Sebastian Berg wrote:
> 
> > On Fri, 2013-05-10 at 19:57 -0400, Neal Becker wrote:
> >> It would be convenient if in arithmetic 0-d arrays were just ignored - it
> >> would seem to me to be convenient in generic code where a degenerate array is
> >> treated as "nothing"
> >> 
> > 
> > Small naming detail. A 0-d array is an array with exactly one element
> > and no dimensions, i.e. np.array(0), and behaves mostly like a scalar.
> > What you have is an empty array with no elements.
> > 
> >> np.zeros ((0,0)) + np.ones ((2,2))
> >> ---------------------------------------------------------------------------
> >> ValueError                                Traceback (most recent call last)
> >> <ipython-input-17-27af0e0bbc6f> in <module>()
> >> ----> 1 np.zeros ((0,0)) + np.ones ((2,2))
> >> 
> >> ValueError: operands could not be broadcast together with shapes (0,0) (2,2)
> >> 
> >> 
> > 
> > I am not sure in what general code you need that, it seems weird to me,
> > since np.zeros((N, N)) + np.ones((2,2)) would also only work if N=1. And
> > if N=1, it looks like it might be a reduction result.
> > Empty arrays *do* support most reductions (making them not empty, like
> > summing them gives 0). And they do broadcast under the normal
> > broadcasting rules, such that np.zeros((0,0)) + np.zeros((10,1,1)) gives
> > np.zeros((10,0,0)).  For the most part, they are not a special case and
> > just work the same as non-empty arrays, which seems right to me.
> > 
> > - Sebastian
> > 
> 
> OK, my code looks like this:
> 
> results = np.dot (a, b) + np.dot (c, d)
> 
> I have a case where I want to basically "turn off" that second dot product, and 
> I thought if c and d were 0-size it should have that effect.
> 

OK, I wouldn't consider that a valid use case to be honest. You could
maybe just set c = d = 0. Heck, you can even have c = np.empty((2, 0)),
d = np.empty((0, 2)) which means that np.dot(c, d) is np.zeros((2,2)),
which for the sake of addition works the same.

But 0-size arrays have way to much meaning to make them identity
operators.

- Sebastian

> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
> 





More information about the NumPy-Discussion mailing list