Faster numpy cartesian to spherical coordinate conversion?

前端 未结 5 1596
南旧
南旧 2020-12-04 15:57

I have an array of 3 million data points from a 3-axiz accellerometer (XYZ), and I want to add 3 columns to the array containing the equivalent spherical coordinates (r, the

5条回答
  •  臣服心动
    2020-12-04 16:16

    Here's a quick Cython code that I wrote up for this:

    cdef extern from "math.h":
        long double sqrt(long double xx)
        long double atan2(long double a, double b)
    
    import numpy as np
    cimport numpy as np
    cimport cython
    
    ctypedef np.float64_t DTYPE_t
    
    @cython.boundscheck(False)
    @cython.wraparound(False)
    def appendSpherical(np.ndarray[DTYPE_t,ndim=2] xyz):
        cdef np.ndarray[DTYPE_t,ndim=2] pts = np.empty((xyz.shape[0],6))
        cdef long double XsqPlusYsq
        for i in xrange(xyz.shape[0]):
            pts[i,0] = xyz[i,0]
            pts[i,1] = xyz[i,1]
            pts[i,2] = xyz[i,2]
            XsqPlusYsq = xyz[i,0]**2 + xyz[i,1]**2
            pts[i,3] = sqrt(XsqPlusYsq + xyz[i,2]**2)
            pts[i,4] = atan2(xyz[i,2],sqrt(XsqPlusYsq))
            pts[i,5] = atan2(xyz[i,1],xyz[i,0])
        return pts
    

    It took the time down from 62.4 seconds to 1.22 seconds using 3,000,000 points for me. That's not too shabby. I'm sure there are some other improvements that can be made.

提交回复
热议问题