[Numpy-discussion] Simple broadcasting? Or not so simple?? [SEC=UNCLASSIFIED]

Robert Kern robert.kern@gmail....
Sun Nov 14 22:07:12 CST 2010


On Sun, Nov 14, 2010 at 21:55,  <Ross.Wilson@ga.gov.au> wrote:
> Dear list,
>
> I thought I understood broadcasting, but now I'm not so sure.
>
> I've simplified as much as I can, so here goes.  I have two input arrays of shape (1, 3, 1).  I want to select elements from one or other of the input arrays depending on whether the corresponding element of a third array exceeds a threshold.  My simplest code is:
> ---------
> import numpy as np
> a = np.array([[[1],[2],[3]]])
> b = np.array([[[4],[5],[6]]])
>
> x = np.array([[[1],[1],[2]]])
>
> result = np.where(x > 1.5, a, b)
> ----------
> and works as expected.
>
> Now, my understanding of broadcasting is that if the 'x' array is defined as np.array([[[1]]]) then broadcasting will ensure the result array will contain elements from array 'b'.  That is, the program will behave as if 'x' had shape of (1,3,1) with three elements each of value 1.  I tested that and got the result I expected.
>
> However, when I ran the test on another machine, it failed with an "array dimensions must agree" error.  On the failing machine numpy.__version__ returns '1.2.0'.  Machines on which the broadcasting works as I expect I see '1.3.0' (or later) in numpy.__version__.
>
> Have broadcast rules changed since 1.2.0?  Or maybe I just don't understand broadcasting?

I'm not certain, but earlier versions of numpy.where() may not have
broadcasted their arguments. Not every function taking arrays as
arguments does broadcasting.

-- 
Robert Kern

"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