将球面坐标转换为笛卡尔坐标然后再转换回笛卡尔坐标并不能给出所需的输出

Far*_*zin 6 python geometry polar-coordinates cartesian-coordinates spherical-coordinate

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

在此输入图像描述

在此输入图像描述

这是我的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
Run Code Online (Sandbox Code Playgroud)

这是我的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
Run Code Online (Sandbox Code Playgroud)

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

>>> 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
Run Code Online (Sandbox Code Playgroud)

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

Dro*_*nir 5

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

  • 我现在记得已经有两个函数“math.radians”和“math. Degrees”也可以进行转换。看起来比乘以常数要干净一些。 (2认同)