Outer or broadcasting?
TLDR
In my test, broadcasting is better.
Speed
v1 = np.random.random((1_000))
v2 = np.random.random((1_000))
%timeit np.add.outer(v1, v2)
%timeit v1[:, np.newaxis] + v2
# 9.81 µs ± 2.08 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# 7.95 µs ± 756 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each
Both code run almost the same, but v1[:, np.newaxis] + v2 might be faster(?)
Numba
from numba import jit
@jit(nopython=True)
def f1(v1, v2): # throw error
return np.add.outer(v1, v2)
def f2(v1, v2): # works
return v1[:, np.newaxis] + v2
The v1[:, np.newaxis] + v2 is Numba compatible.
Note:
v1[:, np.newaxis] + v2 == v1[:, None] + v2.
a[:,np.newaxis] + bto leveragebroadcasting.