Python球坐标与笛卡尔坐标互转 回退后数值与初始值不一致问题
问题错误点及修正方案
- 角度单位不匹配:Python
math模块的三角函数、反三角函数默认使用弧度作为输入输出单位,你测试时直接传入角度值27.5、7.5,未做角度到弧度的转换,是结果不符合预期的核心原因。 - phi计算逻辑冗余错误:
math.atan2(y, x)会自动根据(x,y)所在象限返回[-π, π]区间的正确角度值,你额外新增的x>=0判断以及补π的操作属于错误逻辑,会进一步导致phi计算偏差。 - 默认半径约定:当前你的两个函数默认球坐标半径r=1,若需要适配任意半径的转换可以补充r参数处理。
修正后的代码示例
import math # 球坐标转笛卡尔坐标,输入theta、phi为角度值,默认半径r=1 def spherical_to_cartesian(theta_deg, phi_deg, r=1): theta = math.radians(theta_deg) phi = math.radians(phi_deg) x = r * math.cos(phi) * math.sin(theta) y = r * math.sin(phi) * math.sin(theta) z = r * math.cos(theta) return x, y, z # 笛卡尔坐标转球坐标,输出theta、phi为角度值 def cartesian_to_spherical(x, y, z): r = math.sqrt(x**2 + y**2 + z**2) theta_rad = math.atan2(math.sqrt(x**2 + y**2), z) phi_rad = math.atan2(y, x) # 弧度转角度 theta_deg = math.degrees(theta_rad) phi_deg = math.degrees(phi_rad) # 可选:将角度转为正区间[0, 360) if phi_deg < 0: phi_deg += 360 return theta_deg, phi_deg, r
测试验证
>>> 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.4581060966715388 y=0.06026185132662967 z=0.8870108331781213 >>> theta, phi, r = cartesian_to_spherical(x, y, z) >>> print(f"Spherical coordinates:\ttheta={theta:.3f}\tphi={phi:.3f}") Spherical coordinates: theta=27.500 phi=7.500
内容的提问来源于stack exchange,提问作者Farzin
相关产品推荐
相关产品推荐

