我使用numpy生成θ、半径范围、cos_thetas和sin_thetas。
就获得这些组合而言,我仍然留下了效率非常低的代码。
我曾试图走矢量化的道路,但重塑会让事情变得更糟。
我目前有以下代码:
candidates = []
delta_r = 1
r_min = 50
r_max = 100
num_thetas = 6
# R and Theta ranges
dtheta = int(360 / num_thetas)
## Thetas is bins created from 0 to 360 degree with increment of the dtheta
thetas = np.arange(0, 360, step=dtheta)
## Radius ranges from r_min to r_max
rs = np.arange(r_min, r_max, step=delta_r)
cos_thetas = np.cos(np.deg2rad(thetas))
sin_thetas = np.sin(np.deg2rad(thetas))
for r in rs:
for t in range(num_thetas):
candidates.append((r, int(r * cos_thetas[t]), int(r * sin_thetas[t])))
广播是你的朋友:
d = np.zeros((num_thetas*rs.size, 3), order = "F", dtype = int)
d[:,0] = np.repeat(rs, num_thetas)
d[:,1] = np.ravel(rs[:,None] * cos_thetas[:num_thetas]).astype(int)
d[:,2] = np.ravel(rs[:,None] * sin_thetas[:num_thetas]).astype(int)
尽管远非完美,但这种快速解决方案应该至少能带来一个数量级的改善。
像这样的smth怎么样:
这个例子包含较少的变量值,但您可以调整它。输出是一个数组,但您可以很容易地将其强制转换为列表。
import numpy as np
rs = np.linspace(50, 100, 3)
theta = np.linspace(0, 360, 3)
rs_grid, theta = np.meshgrid(rs, theta)
mgrid = np.stack(
[rs_grid,
rs_grid*np.cos(theta),
rs_grid*np.sin(theta)])
mgrid.T.reshape(-1, 3)
输出:
array([[ 50. , 50. , 0. ],
[ 50. , -29.92300345, -40.05763179],
[ 50. , -14.18455457, 47.94578617],
[ 75. , 75. , 0. ],
[ 75. , -44.88450518, -60.08644768],
[ 75. , -21.27683186, 71.91867926],
[100. , 100. , 0. ],
[100. , -59.84600691, -80.11526357],
[100. , -28.36910915, 95.89157234]])