numpy/numpy — pull request #5371 by shoyer (2014-12-15 07:42:20+00:00)
Title: ENH: add np.broadcast_to and reimplement np.broadcast_arrays

Per the [mailing list discussion](http://mail.scipy.org/pipermail/numpy-discussion/2014-December/071796.html), I have implemented a new function `broadcast_to` that broadcasts an array to a given shape according to numpy's broadcasting rules.

The new array iterator has functionality that could makes several of these functions into *almost* one liners (thank you @jaimefrio, @seberg and @mwiebe for showing how), although we do have to do some extra work to preserve subclasses.

The first commit (eventually to be squashed away) shows how I would implement these *without* relying heavily on `nditer`. It also includes the `broadcast_shape` function (no longer necessary for the implementation of `broadcast_arrays`), which almost but didn't quite work as a one-liner (it failed for size 0 arrays). We could revive it if others think it would serve a useful purpose.

Question: should we allow for broadcasting with negative numbers in the shape? This seems strange but it does work (sort of like reshape) with the current implementation and I suppose someone could find it useful. On the other hand, numbers less than -1 are also supported, which may just be a bug with nditer?

In [1]: import numpy as np

In [2]: x = np.array([1, 2, 3])

# possibly useful
In [3]: np.broadcast_to(x, (-1, -1))
Out[3]: array([[1, 2, 3]])

# probably not
In [4]: np.broadcast_to(x, (-10,))
Out[4]: array([1, 2, 3])

(this functionality currently does not have tests verifying how it works either way.)