Python程序生成球面坐标不工作

1 投票
1 回答
1263 浏览
提问于 2025-04-18 03:11

我正在尝试在Python中生成一些点,这些点位于一个以(0,0)为中心的球体表面上。

# r - the radius of the sphere
def createSphere(r):
    lst = []
    for z in range(-r, r+1):

        r_ = r - abs(z)
        if r_ == 0:
            lst.append((0,0,r*np.sign(z)))
        else:
            for d in range(r_):
                lst.append((r_ * cos(d * (360/float(r_))), r_ * sin(d * 360/float(r_))), z)            )
    return lst

这个代码会返回一个列表,格式是[(x1,y1,z1),...]。

结果大概是这样的: 这里输入图片描述

但是这个球的表面看起来不光滑,反而像是一个有尖角的立方体。

有没有人知道这是怎么回事?

谢谢!

1 个回答

4

使用标准的球坐标到笛卡尔坐标的转换

import math
pi = math.pi
sin = math.sin
cos = math.cos

def createSphere(r, N=10):
    lst = []
    thetas = [(2*pi*i)/N for i in range(N)]
    phis = [(pi*i)/N for i in range(N)]
    for theta in thetas:
        for phi in phis:
            x = r * sin(phi) * cos(theta)
            y = r * sin(phi) * sin(theta)
            z = r * cos(phi)
            lst.append((x, y, z))
    return lst

根据下面的评论:如果你想根据高度(或者说phi)来改变点的数量,可以让thetas依赖于phi

def createSphere(r, N=10):
    lst = []
    for phi in [(pi*i)/(N-1) for i in range(N)]:
        M = int(sin(phi)*(N-1))+1
        for theta in [(2*pi*i)/M for i in range(M)]:
            x = r * sin(phi) * cos(theta)
            y = r * sin(phi) * sin(theta)
            z = r * cos(phi)
            lst.append((x, y, z))
    return lst

上面提到的关键行是

M = int(sin(phi)*(N-1))+1

phi为0或pi时,M的值为1;而当phi等于pi/2(在“赤道”上)时,M的值为N。需要注意的是,这只是定义M的一种可能方式。你可以不使用sin,而是定义一个分段线性函数,保持相同的边界值,比如……

撰写回答