这不能在不重新实现的情况下进行矢量化interp_2d
。但是,假设interp_2d
是某种类型的插值,那么操作可能是线性的。这lambda z0: interp_2d(x0, y0, z0, x1, y1)
可能等同于np.dot(M, z0)
where is some(可能是稀疏的)矩阵,M
它取决于x0
、和。现在,通过调用该函数,您在每次调用时都会隐式地重新计算该矩阵,即使它每次都相同。找出该矩阵是什么并多次将其重新应用于新矩阵会更有效。y0
x1
y1
interp_2d
z0
这是一个非常简单的一维插值示例:
x0 = [0., 1.]
x1 = 0.3
z0_2d = "some very long array with shape=(2, n)"
def interp_1d(x0, z0, x1):
"""x0 and z0 are length 2, 1D arrays, x1 is a float between x0[0] and x0[1]."""
delta_x = x0[1] - x0[0]
w0 = (x1 - x0[0]) / delta_x
w1 = (x0[1] - x1) / delta_x
return w0 * z0[0] + w1 * z0[1]
# The slow way.
for i in range(n):
z1_2d[i] = interp_1d(x0, z0_2d[:,i], x1)
# Notice that the intermediate products w1 and w2 are the same on each
# iteration but we recalculate them anyway.
# The fast way.
def interp_1d_weights(x0, x1):
delta_x = x0[1] - x0[0]
w0 = (x1 - x0[0]) / delta_x
w1 = (x0[1] - x1) / delta_x
return w0, w1
w0, w1 = interp_1d_weights(x0, x1)
z1_2d = w0 * z0_2d[0,:] + w1 * z0_2d[1:0]
如果n
非常大,预计速度会超过 100 倍。