使用 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
Run Code Online (Sandbox Code Playgroud)
我发现了一个对数组进行子集化的技巧:
ind = sum(points.^2,dims=2) .<= pi^2
## ideally I wouldn't have to do this:
ind_ = dropdims(ind,dims=2)
Run Code Online (Sandbox Code Playgroud)
但是,原则上数组索引应该是单行的。我怎样才能在 Julia 中做得更好?
问题是您正在创建一个二维索引向量。您可以通过使用来避免它eachrow:
ind = sum.(eachrow(points.^2)) .<= pi^2
Run Code Online (Sandbox Code Playgroud)
所以你的完整答案是:
function spherical_sample(N::Int64)
points = pi*(2*rand(5*N,3).-1.0)
ind = sum.(eachrow(points.^2)) .<= pi^2
return points[ind,:][1:N,:]
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
201 次 |
| 最近记录: |