gpt4 book ai didi

python - 为什么这个 python 代码在笛卡尔坐标和球坐标之间转换时给出了错误的答案?

转载 作者:太空宇宙 更新时间:2023-11-04 01:51:58 26 4
gpt4 key购买 nike

所以我在 python3.4 中设置了两个函数,Cartesian2SphericalSpherical2Cartesian,以帮助我将笛卡尔坐标系和球坐标系之间的点转换为需要大量此类坐标转换的应用程序。这是函数的代码。我正在使用 this Wikipedia article作为我进行转换的来源。

def Cartesian2Spherical(p):
# p = (x,y,z)
# theta in (0,pi) and phi in (0,2pi)
x,y,z = p
r = np.sqrt(x*x+y*y+z*z)
theta = arctan2(y,x) # Inclination
phi = arccos(z/r) # Azimuth
q = np.array([r,theta,phi])
return q

def Spherical2Cartesian(q):
# q = (r,theta,phi)
# theta in (0,pi) and phi in (0,2pi)
r,theta,phi = q
SinTheta = sin(theta)
CosTheta = cos(theta)
SinPhi = sin(phi)
CosPhi = cos(phi)
rSinTheta = r*SinTheta
x = rSinTheta*CosPhi
y = rSinTheta*SinPhi
z = r*CosTheta
p = np.array([x,y,z])
return p

如您所见,它们非常简单。尽管代码非常简单,但是,在几次测试运行中,我仍然从中得到了奇怪的结果。最终,当我决定用这些函数做一个简单的测试时,我的 bug 搜索停止了:我让 python 打印一些点 p 然后是 Spherical2Cartesian(Cartesian2Spherical(p)) 结果是这样的:

  [1.11022302e-16 1.47224319e+00 2.22044605e-16]
[9.01488953e-17 1.47224319e+00 9.01488953e-17]

一方面,我很高兴找到了这个错误,但现在我很困惑,因为我不知道在这么简单的一段代码中可能有什么问题。有人可以帮我解决这个问题吗?

最佳答案

看起来您翻转了 theta 和 phi 的转换。试试这个。

def Cartesian2Spherical(p):
# p = (x,y,z)
# theta in (0,pi) and phi in (0,2pi)
x,y,z = p
r = np.sqrt(x*x+y*y+z*z)
phi = np.arctan2(y,x) # Inclination
theta = np.arccos(z/r) # Azimuth
q = np.array([r,theta,phi])
return q

def Spherical2Cartesian(q):
# q = (r,theta,phi)
# theta in (0,pi) and phi in (0,2pi)
r,theta,phi = q
SinTheta = np.sin(theta)
CosTheta = np.cos(theta)
SinPhi = np.sin(phi)
CosPhi = np.cos(phi)
rSinTheta = r*SinTheta
x = rSinTheta*CosPhi
y = rSinTheta*SinPhi
z = r*CosTheta
p = np.array([x,y,z])
return p

p = (1,1,1)

print(Spherical2Cartesian(Cartesian2Spherical(p)))

输出:

[1. 1. 1.]

关于python - 为什么这个 python 代码在笛卡尔坐标和球坐标之间转换时给出了错误的答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57794357/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com