【发布时间】:2017-03-03 03:54:02
【问题描述】:
我有一些代码可以生成圆柱对称曲面的坐标,坐标为 (r, theta, phi)。目前,我生成一个 phi 切片的坐标,并将其存储在一个 2xN 数组中(对于 N 个 bin),然后在一个 for 循环中,我将这个数组从 0 复制到 2pi 的每个 phi 值:
import numpy as np
# this is the number of bins that my surface is chopped into
numbins = 50
# these are the values for r
r_vals = np.linspace(0.0001, 50, numbins, endpoint = True)
# these are the values for theta
theta_vals = np.linspace(0, np.pi / 2, numbins, endpoint = True)
# I combine the r and theta values into a 2xnumbins array for one "slice" of phi
phi_slice = np.vstack([r_vals,theta_vals]).T
# this is the array which will store all of the coordinates of the surface
surface = np.zeros((numbins**2,3))
lower_bound = 0
upper_bound = numbins
# this is the size of the bin for phi
dphi = (2 * np.pi) / numbins
# this is the for loop I'd like to eliminate.
# For every value of phi, it puts a copy of the phi_slice array into
# the surface array, so that the surface is cylindrical about phi.
for phi in np.linspace(0, (2 * np.pi) - dphi, numbins):
surface[lower_bound:upper_bound, :2] = phi_slice
surface[lower_bound:upper_bound,2] = phi
lower_bound += numbins
upper_bound += numbins
我在 1e6 或 1e7 步的数值积分中调用此例程,虽然在上面的示例中 numbins 是 50,但实际上它会是数千。这个 for 循环是一个瓶颈,我真的很想消除它以加快速度。有没有一种很好的 NumPythonic 方法来做与这个 for 循环相同的事情?
【问题讨论】:
-
我投票决定将此问题作为离题结束,因为该问题属于 Stack Exchange 网络中的另一个站点:codereview.stackexchange.com
-
留在这里;从 numpy 代码中消除循环是一个常见的 SO 问题。这里有更多的 numpy 专家。
-
但是,如果示例是 MCVe,它会有所帮助 - 最小、完整、可验证。这样我们就可以轻松地复制粘贴、测试结果和测试更改。显示一些输入和输出。
-
仅通过阅读代码很难想象发生了什么。它需要更简单一些具体的值。添加一些说明。你循环了多少次?
-
感谢您的反馈!我已经编辑过了,现在是 MCV;让我知道我是否可以详细说明。
标签: python arrays numpy for-loop