繁体   English   中英

如何操作 3D 数组以将笛卡尔坐标转换为球坐标

[英]How to manipulate a 3D array to convert from cartesian coordinates to spherical coordinates

所以我是 Python 的新手,我想将包含笛卡尔坐标的 3D 数组转换为球坐标。 我已经完成了这个计算转换的函数:

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

但是,如果我有一个随机数组 (N,N,N),例如

N = 3   
array = np.random.rand(N, N, N).astype(dtype=np.float16)

并将 x、y 和 z 坐标传递给我的函数以从笛卡尔坐标转换为球面坐标

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,y,z)
 

我不断收到错误的转换结果。 我尝试了不同的方法,但仍然无法弄清楚我做错了什么。

我已经用唯一的 (x, y, z) 检查了该函数,它似乎转换为 (r, theta, phi) 就好了。

我认为您的问题在于您如何获得随机数(x,y,z)。 也许尝试这样的事情:

import numpy as np

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

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,y,z)

print('\nCartesian:')
print('x',x,'\ny',y,'\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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM