使用Julia语言,我定义了一个函数,使用拒绝抽样方法,在半径为3.14的球内均匀采样点,代码如下:
function spherical_sample(N::Int64)
# generate N points uniformly distributed inside sphere
# using rejection sampling:
points = pi*(2*rand(5*N,3).-1.0)
ind = sum(points.^2,dims=2) .<= pi^2
## ideally I wouldn't have to do this:
ind_ = dropdims(ind,dims=2)
return points[ind_,:][1:N,:]
end
我找到了一个有关数组子集的技巧:
ind = sum(points.^2,dims=2) .<= pi^2
## ideally I wouldn't have to do this:
ind_ = dropdims(ind,dims=2)
但原则上数组索引应该只需要一行代码。我如何在Julia中更好地实现这个功能呢?
ind
中取前N
个元素,如sum(x->x^2, points, dims=2) .<= pi^2)[1:N]
(它还会丢弃一个维度并避免过多分配临时矩阵)。但仍然不能保证ind
有N
个元素,因此这通常会产生错误 - 请参见我的下面评论。 - Bogumił Kamiński(sum(x->x^2, points, dims=2) .<= pi^2)[1:N]
并不能提供帮助,因为这个选择向量需要包含超过 N 个元素(而且有时仍可能失败)。 - Przemyslaw Szufel