Regardless of whether your function is vectorized, you can use an approach with np.indices
like this:
base_grid = np.indices(7 * (3,), sparse=False) - 1
This produces an array of all the combinations of -1, 0, 1
that you need. np.meshgrid
does something similar, but the arrays will be separated into a tuple, which is inconvenient.
At each iteration, you modify the grid with your step (scale) and offset:
current_grid = base_grid * scale + offset
If your function is vectorized, you call it directly, the grid is 7 3x3x3x3x3x3x3 arrays. If it accepts seven inputs, just use star expansion.
If your function is not vectorized, you can still step along the corresponding elements in a single loop, not seven loops, using np.nditer
:
with np.nditer([current_grid, None],
op_axes=[list(range(1, current_grid.ndim)), None]) as it:
for x, y in it:
y[:] = f(*x)
j = it.operands[1]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…