gpt4 book ai didi

python - 在球形体积内采样均匀分布的随机点

转载 作者:IT老高 更新时间:2023-10-28 21:49:05 26 4
gpt4 key购买 nike

我希望能够生成落在球形体积内的粒子位置的随机均匀样本。

下面的图片(由 http://nojhan.free.fr/metah/ 提供)显示了我正在寻找的内容。这是穿过球体的切片,显示点的均匀分布:

Uniformly distributed circle

这是我目前得到的:

Uniformly Distributed but Cluster Of Points

由于球坐标和笛卡尔坐标之间的转换,您可以看到中心有一个点簇。

我使用的代码是:

def new_positions_spherical_coordinates(self):
radius = numpy.random.uniform(0.0,1.0, (self.number_of_particles,1))
theta = numpy.random.uniform(0.,1.,(self.number_of_particles,1))*pi
phi = numpy.arccos(1-2*numpy.random.uniform(0.0,1.,(self.number_of_particles,1)))
x = radius * numpy.sin( theta ) * numpy.cos( phi )
y = radius * numpy.sin( theta ) * numpy.sin( phi )
z = radius * numpy.cos( theta )
return (x,y,z)

下面是一些 MATLAB 代码,据说可以创建一个均匀的球形样本,它类似于 http://nojhan.free.fr/metah 给出的方程.我似乎无法破译或理解他们做了什么。

function X = randsphere(m,n,r)

% This function returns an m by n array, X, in which
% each of the m rows has the n Cartesian coordinates
% of a random point uniformly-distributed over the
% interior of an n-dimensional hypersphere with
% radius r and center at the origin. The function
% 'randn' is initially used to generate m sets of n
% random variables with independent multivariate
% normal distribution, with mean 0 and variance 1.
% Then the incomplete gamma function, 'gammainc',
% is used to map these points radially to fit in the
% hypersphere of finite radius r with a uniform % spatial distribution.
% Roger Stafford - 12/23/05

X = randn(m,n);
s2 = sum(X.^2,2);
X = X.*repmat(r*(gammainc(s2/2,n/2).^(1/n))./sqrt(s2),1,n);

如果有任何关于在 Python 中从球形体积生成真正均匀样本的建议,我将不胜感激。

似乎有很多例子展示了如何从均匀的球壳中取样,但这似乎更容易成为更容易的问题。问题与缩放有关 - 半径为 0.1 的粒子应该比半径为 1.0 的粒子少,才能从球体的体积中生成均匀的样本。

编辑:修正并删除了我通常要求的事实,我的意思是制服。

最佳答案

虽然我更喜欢球体的丢弃方法,但为了完整性I offer the exact solution .

在球坐标中,利用 sampling rule :

phi = random(0,2pi)
costheta = random(-1,1)
u = random(0,1)

theta = arccos( costheta )
r = R * cuberoot( u )

现在你有一个 (r, theta, phi) 组,它可以按通常的方式转换为 (x, y, z)

x = r * sin( theta) * cos( phi )
y = r * sin( theta) * sin( phi )
z = r * cos( theta )

关于python - 在球形体积内采样均匀分布的随机点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5408276/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com