5

我正在尝试编写两个函数来将笛卡尔坐标转换为球坐标,反之亦然。以下是我用于转换的方程式(也可以在此Wikipedia 页面上找到):

在此处输入图像描述

在此处输入图像描述

这是我的spherical_to_cartesian功能:

def spherical_to_cartesian(theta, phi):
    x = math.cos(phi) * math.sin(theta)
    y = math.sin(phi) * math.sin(theta)
    z = math.cos(theta)
    return x, y, z

这是我的cartesian_to_spherical功能:

def cartesian_to_spherical(x, y, z):
    theta = math.atan2(math.sqrt(x ** 2 + y ** 2), z)
    phi = math.atan2(y, x) if x >= 0 else math.atan2(y, x) + math.pi
    return theta, phi

而且,这是驱动程序代码:

>>> t, p = 27.500, 7.500
>>> x, y, z = spherical_to_cartesian(t, p)
>>> print(f"Cartesian coordinates:\tx={x}\ty={y}\tz={z}")
Cartesian coordinates:  x=0.24238129061573832   y=0.6558871334524494    z=-0.7148869687796651
>>> theta, phi = cartesian_to_spherical(x, y, z)
>>> print(f"Spherical coordinates:\ttheta={theta}\tphi={phi}")
Spherical coordinates:  theta=2.367258771281654 phi=1.2168146928204135

我无法弄清楚为什么我得到的thetaphi值与我的初始值不同(输出值甚至不接近输入值)。我是否在我的代码中犯了一个我看不到的错误?

4

2 回答 2

4

您似乎以度为单位给出角度,而所有三角函数都需要弧度。度数乘以math.pi/180得到弧度,弧度乘以180/math.pi得到度数。

于 2021-10-06T09:28:33.203 回答
-1

结果是正确的,但您应该使用模 pi 运算检查它们的值。

包中的三角函数math期望以弧度为单位的输入角度。这意味着您的角度大于2*pi并等于通过加法或减法获得的任何其他值2*pi(这也表示以弧度为单位的完整旋转)。

特别是你有:

>>> 27.5 % (2*math.pi)
2.367258771281655

>>> 7.500 % (2*math.pi)
1.2168146928204138
于 2021-10-06T09:28:45.083 回答