# [Numpy-discussion] Faster way to generate a rotation matrix?

Hoyt Koepke hoytak@gmail....
Wed Mar 4 00:43:25 CST 2009

```> def rotation(theta, R = np.zeros((3,3))):
>    cx,cy,cz = np.cos(theta)
>    sx,sy,sz = np.sin(theta)
>    R.flat = (cx*cz - sx*cy*sz, cx*sz + sx*cy*cz, sx*sy,
>        -sx*cz - cx*cy*sz, -sx*sz + cx*cy*cz,
>        cx*sy, sy*sz, -sy*cz, cy)
>    return R
>
> Pretty evil looking ;) but still wouldn't mind somehow getting it faster

in cython, the above would be (something like):

from numpy cimport ndarray

cdef extern from "math.h":
double cos(double)
double sin(double)

def rotation(ndarry[double] theta, ndarray[double, ndim=2] R = np.zeros((3,3))):
cdef double cx = cos(theta[0]), cy = cos(theta[1]), cz = cos(theta[2])
cdef double sx = sin(theta[0]), sy = sin(theta[1]), sz = sin(theta[2])

R[0,0] = cx*cz - sx*cy*sz
R[0,1] = cx*sz + sx*cy*cz

R.flat = (cx*cz - sx*cy*sz, cx*sz + sx*cy*cz, sx*sy,
-sx*cz - cx*cy*sz, -sx*sz + cx*cy*cz,
cx*sy, sy*sz, -sy*cz, cy)
return R
>
> Pretty evil looking ;) but still wouldn't mind somehow getting it faster

> One of the usual recommendation on the python list is also to load
> functions into the local scope to avoid the lookup in the module.

> also you still have a few duplicate multiplications, e.g. cx*cz, cx*sz, ..?
> but this looks already like micro optimizatio

++++++++++++++++++++++++++++++++++++++++++++++++
+ Hoyt Koepke
+ University of Washington Department of Statistics
+ http://www.stat.washington.edu/~hoytak/
+ hoytak@gmail.com
++++++++++++++++++++++++++++++++++++++++++
```

More information about the Numpy-discussion mailing list