デカルト座標を球座標に、またはその逆に変換するための 2 つの関数を作成しようとしています。変換に使用した方程式は次のとおりです (このウィキペディアのページにもあります)。
と
これが私の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
シータとファイの値が初期値と異なる理由がわかりません (出力値が入力値に近くさえありません)。見えないコードで間違いを犯しましたか?