pythoncoordinate-transformation

Why does this python code gives the wrong answer when converting between cartesian and spherical coordinates?


So I set up two functions in python3.4, Cartesian2Spherical and Spherical2Cartesian, in order to help me convert a point between cartesian ans spherical coordinate systems as part of an application that required lots of such coordinate transformations. Here is the code for the functions. I am using this Wikipedia article as my source for the transformations.

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

As you can see, they are pretty straightforward. Even though the code is so simple, however, I still got weird results from them during several test runs. Eventually my bug hunt came to a halt when I decided to do a simple test with these functions: I asked python to print some point p followed by Spherical2Cartesian(Cartesian2Spherical(p)) and the result was this:

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

for one I am happy for having tracked the bug down, but now I am very confused because I have no clue as to what could possibly be wrong in such a simple piece of code. Could someone be kind enough to walk me through this?


Solution

  • It looks like you flipped your transformations for theta and phi. Try this.

    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)))
    

    Output:

    [1. 1. 1.]