如何在球体中生成点并用pyplot绘制它们?

2024-04-19 21:00:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我用这个方法给我一个球内点的列表。然而,当我绘制结果时,它看起来并不是球形的。这里的逻辑一定有问题。可能是什么?在

def give_sphere(x, y, z, r, num):
    """The distribution of dots in the sphere increases towards the center.
    Return: A List of Points (x,y,z) which are all inside the sphere."""
    points = []
    for i in range(0, num):
        factor = normedgauss()        # A value between 0 and 1 following a gaussian
        ir = r * factor
        ix = x + ir * np.cos(npi())
        iy = y + ir * np.sin(npi())
        iz = z + ir * np.cos(npi())
        points.append((ix, iy, iz))
    return points

这是3D绘图: enter image description here 我还想在3D中使用pyplot绘制这个点列表,我可以用下面的代码来实现,但是我不能添加另一个点云来显示在同一个图中。我要怎么做?在

^{pr2}$

Tags: ofthein列表irnp绘制cos
2条回答

可能你是用均匀分布的随机数生成角度,事实并非如此。3D中的体积差是类似于(dr^3)(d cos theta) (d phi),这意味着均匀分布的变量是cos theta,而不是{}(径向分量也是如此,但我不确定你想做什么,所以我没有做过任何改动)

def give_sphere(x, y, z, r, num):
    points = []
    for i in range(0, num):
        factor = normedgauss()        # A value between 0 and 1 following a gaussian
        ir = r * factor
        itheta = np.arccos(np.random.uniform(-1, 1))
        iphi = np.random.uniform(0, 2 * np.pi)
        ix = x + ir * np.sin(itheta) * np.cos(iphi)
        iy = y + ir * np.sin(itheta) * np.sin(iphi)
        iz = z + ir * np.cos(itheta)
        points.append((ix, iy, iz))
    return points

记住这一点,这就是你应该得到的

enter image description here

至于第二个问题

^{pr2}$

enter image description here

你的第一个问题是关于基于分布函数的蒙特卡罗模拟。一般情况下,需要使用概率密度函数来推导特定的抽样方案。在

我假设你希望在一个球体内有均匀分布的点。我推荐一个最好的链接,它清楚地展示了你的案例的整个过程,并鼓励你探索利弊:
Generating uniformly distributed numbers on a sphere。在

相关问题 更多 >