![](/img/trans.png)
[英]How can I interpolate array from spherical to cartesian coordinates with Python?
[英]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.