gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:21:49 24 4
gpt4 key购买 nike

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

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 绘制这个点列表。我可以使用以下代码来实现这一点,但随后我无法添加另一个点云以在同一图表中显示。我将如何做到这一点?

def plot_sphere(points):
x_list = [x for [x, y, z] in points]
y_list = [y for [x, y, z] in points]
z_list = [z for [x, y, z] in points]

fig = plt.figure()
ax = Axes3D(fig)

ax.scatter(x_list, y_list, z_list)
plt.show()

最佳答案

您可能正在使用均匀分布的随机数生成角度,但事实并非如此。 3D 中的体积微分类似于 (dr^3)(d cos theta) (d phi),这意味着均匀分布的变量是 cos theta,不是 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

至于第二个问题

def plot_sphere(points, ax):
x_list = [x for [x, y, z] in points]
y_list = [y for [x, y, z] in points]
z_list = [z for [x, y, z] in points]

ax.scatter(x_list, y_list, z_list)


fig = plt.figure()
ax = Axes3D(fig)


points1 = give_sphere(0, 0, -2, 1, 1000)
points2 = give_sphere(0, 0, 2, 1, 1000)
plot_sphere(points1, ax)
plot_sphere(points2, ax)

plt.show()

enter image description here

关于python - 如何在球体中生成点并用 pyplot 绘制它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53747715/

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