【发布时间】:2021-11-26 11:12:17
【问题描述】:
我正在尝试编写两个函数来将笛卡尔坐标转换为球坐标,反之亦然。以下是我用于转换的方程式(也可以在 Wikipedia page 上找到):
和
这是我的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
我不明白为什么我得到的 theta 和 phi 值与我的不同初始值(输出值甚至不接近输入值)。我是否在我的代码中犯了一个我看不到的错误?
【问题讨论】:
-
问得真好。
-
顺便说一句,看看这个小功能:如果你把
{theta=}放在你的格式化字符串中,它和theta={theta}做同样的事情。
标签: python geometry polar-coordinates cartesian-coordinates spherical-coordinate