Search code examples
pythonnumpymultidimensional-arraycartesian-coordinatesspherical-coordinate

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


So I'm new to Python and I'd like to convert a 3D-array containing cartesian coordinates to spherical coordinates. I have done this function that calculates the conversion:

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

However, if I have a random array (N,N,N), such as

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

And pass the x, y and z coordinates to my function to convert from cartesian to spherical

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)
 

I keep getting wrong conversion results. I've tried different approaches but still couldn't figure out what I am doing wrong.


Solution

  • I have checked the function with a unique (x, y, z) and it seems to be converting to (r, theta, phi) just fine.

    I think your problem is on how are you getting the random (x, y, z). Maybe try something like this:

    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)
    

    Output:

    array_np: [0.2864 0.938 0.9243]

    Cartesian: x 0.2864 y 0.938 z 0.9243

    Spherical: (1.3476626409849026, 1.274, 0.8150028593437515)