我想加速以下处理r
光线和n
球体的计算。到目前为止,我得到的是:
# shape of mu1 and mu2 is (r, n)
# shape of rays is (r, 3)
# note that intersections has 2n columns because for every sphere one can
# get up to two intersections (secant, tangent, no intersection)
intersections = np.empty((r, 2*n, 3))
for col in range(n):
intersections[:, col, :] = rays * mu1[:, col][:, np.newaxis]
intersections[:, col + n, :] = rays * mu2[:, col][:, np.newaxis]
# [...]
# calculate euclidean distance from the center of gravity (0,0,0)
distances = np.empty((r, 2 * n))
for col in range(n):
distances[:, col] = np.linalg.norm(intersections[:, col], axis=1)
distances[:, col + n] = np.linalg.norm(intersections[:, col + n], axis=1)
我试图通过避免for
循环来加快速度,但却不知道如何正确地广播数组,所以我只需要一个函数调用。非常感谢您的帮助。你知道吗
下面是使用^{} 的矢量化方法-
最后一步可以用^{} 来代替,就像这样-
或者用
np.einsum
替换几乎所有的东西,换成另一种矢量化的方式,就像这样-运行时测试和验证输出-
计时-
相关问题 更多 >
编程相关推荐