Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
|
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
我希望能够生成落在球形体积内的粒子位置的随机均匀样本。
下图(由http://nojhan.free.fr/metah/提供 )显示了我正在寻找的内容。这是穿过球体的切片,显示了点的均匀分布: ![]() 这是我目前得到的: ![]() 可以看到,由于球面坐标和笛卡尔坐标之间的转换,因此在中心存在一簇点。 我使用的代码是: 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的粒子少,以便从球体的体积生成均匀的样本。 编辑:修复并删除了我通常要求的事实,我的意思是统一。 回答: 尽管我更喜欢球体的丢弃方法,但为了完整性, 我提供了精确的解决方案 。 在球形坐标中,利用采样规则 : 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 ) 更多&回答... |
![]() |
![]() |