问题描述
所以我是 Python 新手,我想将包含笛卡尔坐标的 3D 数组转换为球坐标。我已经完成了这个计算转换的函数:
if result in msg.content:
TypeError: 'in <string>' requires string as left operand,not list
def cart2sph(x,y,z):
xy = np.sqrt(x**2 + y**2) # sqrt(x² + y²)
x_2 = x**2
y_2 = y**2
z_2 = z**2
r = np.sqrt(x_2 + y_2 + z_2) # r = sqrt(x² + y² + z²)
theta = np.arctan2(y,x)
phi = np.arctan2(xy,z)
return r,theta,phi
并将 x、y 和 z 坐标传递给我的函数以从笛卡尔坐标转换为球面
N = 3
array = np.random.rand(N,N).astype(dtype=np.float16)
我不断收到错误的转换结果。我尝试了不同的方法,但仍然无法弄清楚我做错了什么。
解决方法
我已经用唯一的 (x,y,z) 检查了该函数,它似乎可以很好地转换为 (r,theta,phi)。
我认为您的问题在于您如何获得随机数 (x,z)。也许尝试这样的事情:
import numpy as np
def cart2sph(x,z):
xy = np.sqrt(x**2 + y**2) # sqrt(x² + y²)
x_2 = x**2
y_2 = y**2
z_2 = z**2
r = np.sqrt(x_2 + y_2 + z_2) # r = sqrt(x² + y² + z²)
theta = np.arctan2(y,x)
phi = np.arctan2(xy,z)
return r,phi
N = 3
array_np = np.random.rand(N).astype(dtype=np.float16)
print('array_np:')
print(array_np)
x = np.asarray(array_np)[0].astype(dtype=np.float16)
y = np.asarray(array_np)[1].astype(dtype=np.float16)
z = np.asarray(array_np)[2].astype(dtype=np.float16)
sphere_coord = cart2sph(x,z)
print('\nCartesian:')
print('x',x,'\ny','\nz',z)
print('\nSpherical:')
print(sphere_coord)
输出:
array_np:[0.2864 0.938 0.9243]
笛卡尔坐标:x 0.2864 y 0.938 z 0.9243
球形:(1.3476626409849026,1.274,0.8150028593437515)