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

标签 python matlab random geometry uniform-distribution

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

下面的图片(由 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/

相关文章:

php - 从文件中获取唯一的随机行并使用 php 将它们写入另一个文件

python - 加入列表列表和另一个列表?

python - 使用 python 将数据分组到文本文件中

matlab - 在 MATLAB 中创建充满任意数据的大型 txt 文件

matlab - 复制向量并将每个副本向下移动 1 行,无需 for 循环

javascript - 如何根据匹配参数从数组中选择几个随机 id 值?

python - django queryset values()方法字段顺序与返回的顺序不同

jquery - 为什么 json.dumps() 在使用变量时会抛出 500 内部服务器错误?

c++ - 如何使用 'Build Model' 函数从 matlab simulink block 生成 c/c++ 代码?

来自特定数组的 C++ 随机数生成器