为什么这个 python 代码在笛卡尔坐标和球坐标之间转换时给出了错误的答案?

Why does this python code gives the wrong answer when converting between cartesian and spherical coordinates?

所以我在 python3.4 中设置了两个函数,Cartesian2SphericalSpherical2Cartesian,以帮助我将笛卡尔坐标系和球坐标系之间的点转换为需要大量此类坐标转换的应用程序。这是函数的代码。我使用 this Wikipedia article 作为转换的来源。

def Cartesian2Spherical(p):
    # p = (x,y,z)
    # theta  in (0,pi) and phi in (0,2pi)
    x,y,z = p
    r = np.sqrt(x*x+y*y+z*z)
    theta = arctan2(y,x)  # Inclination
    phi = arccos(z/r)  # Azimuth
    q = np.array([r,theta,phi])
    return q

def Spherical2Cartesian(q):
    # q = (r,theta,phi)
    # theta  in (0,pi) and phi in (0,2pi)
    r,theta,phi = q
    SinTheta = sin(theta)
    CosTheta = cos(theta)
    SinPhi = sin(phi)
    CosPhi = cos(phi)
    rSinTheta = r*SinTheta
    x = rSinTheta*CosPhi
    y = rSinTheta*SinPhi
    z = r*CosTheta
    p  = np.array([x,y,z])
    return p

如您所见,它们非常简单。尽管代码非常简单,但是,在几次测试运行中,我仍然从中得到了奇怪的结果。最终,当我决定用这些函数做一个简单的测试时,我的 bug 搜索停止了:我要求 python 打印一些点 p,然后是 Spherical2Cartesian(Cartesian2Spherical(p)),结果是这样的:

  [1.11022302e-16 1.47224319e+00 2.22044605e-16]
  [9.01488953e-17 1.47224319e+00 9.01488953e-17]

一方面,我很高兴找到了这个错误,但现在我很困惑,因为我不知道在这么简单的一段代码中可能有什么问题。有人可以帮我解决这个问题吗?

您似乎翻转了 theta 和 phi 的变换。试试这个。

def Cartesian2Spherical(p):
    # p = (x,y,z)
    # theta  in (0,pi) and phi in (0,2pi)
    x,y,z = p
    r = np.sqrt(x*x+y*y+z*z)
    phi = np.arctan2(y,x)  # Inclination
    theta = np.arccos(z/r)  # Azimuth
    q = np.array([r,theta,phi])
    return q

def Spherical2Cartesian(q):
    # q = (r,theta,phi)
    # theta  in (0,pi) and phi in (0,2pi)
    r,theta,phi = q
    SinTheta = np.sin(theta)
    CosTheta = np.cos(theta)
    SinPhi = np.sin(phi)
    CosPhi = np.cos(phi)
    rSinTheta = r*SinTheta
    x = rSinTheta*CosPhi
    y = rSinTheta*SinPhi
    z = r*CosTheta
    p  = np.array([x,y,z])
    return p

p = (1,1,1) 

print(Spherical2Cartesian(Cartesian2Spherical(p)))

输出:

[1. 1. 1.]