我相对于Python还是新手,我有一个嵌套的for循环。由于for循环运行时间较长,我正在尝试找到一种向量化此代码的方法,以使其运行更快。
在这种情况下,coord是一个三维数组,其中coord[x, 0, 0]和coord[x, 0, 1]是整数,coord[x, 0, 2]是0或1。H是SciPy稀疏矩阵,x_dist、y_dist、z_dist和a都是浮点数。
在这种情况下,coord是一个三维数组,其中coord[x, 0, 0]和coord[x, 0, 1]是整数,coord[x, 0, 2]是0或1。H是SciPy稀疏矩阵,x_dist、y_dist、z_dist和a都是浮点数。
# x_dist, y_dist, and z_dist are floats
# coord is a num x 1 x 3 numpy array where num can go into the hundreds of thousands
num = coord.shape[0]
H = sparse.lil_matrix((num, num))
for i in xrange(num):
for j in xrange(num):
if (np.absolute(coord[i, 0, 0] - coord[j, 0, 0]) <= 2 and
(np.absolute(coord[i, 0, 1] - coord[j, 0, 1]) <= 1)):
x = ((coord[i, 0, 0] * x_dist + coord[i, 0, 2] * z_dist) -
(coord[j, 0, 0] * x_dist + coord[j, 0, 2] * z_dist))
y = (coord[i, 0, 1] * y_dist) - (coord[j, 0, 1] * y_dist)
if a - 0.5 <= np.sqrt(x ** 2 + y ** 2) <= a + 0.5:
H[i, j] = -2.7
我还了解到使用NumPy进行广播虽然速度更快,但会导致大量的临时数组内存使用。是选择向量化路线更好,还是尝试使用类似Cython的东西?