【问题标题】:Converting spherical coordinates into Cartesian and then converting back into Cartesian isn't giving the desired output将球面坐标转换为笛卡尔坐标然后再转换回笛卡尔坐标并不能提供所需的输出
【发布时间】: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

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

【问题讨论】:

  • 问得真好。
  • 顺便说一句,看看这个小功能:如果你把{theta=}放在你的格式化字符串中,它和theta={theta}做同样的事情。

标签: python geometry polar-coordinates cartesian-coordinates spherical-coordinate


【解决方案1】:

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

【讨论】:

  • 我现在记得已经有两个函数,math.radiansmath.degrees 也可以进行转换。看起来比乘以常数要干净一些。
【解决方案2】:

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

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

特别是你有:

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

>>> 7.500 % (2*math.pi)
1.2168146928204138

【讨论】:

  • OP 的输入显然是度数,而不是多次旋转的弧度。此外,如果它们是,这些功能仍然可以正常工作。
  • 我只是想表明转换工作正常。
  • 问题中没有提到角度单位,所以我不会假设。
  • 你是对的,但度数/弧度的混淆似乎至少值得一提。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多