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

Robert Kern robert.kern@gmail....
Tue Mar 3 22:57:23 CST 2009

```On Tue, Mar 3, 2009 at 22:41, Jonathan Taylor
<jonathan.taylor@utoronto.ca> wrote:
> Thanks,  All these things make sense and I should have known to
> calculate the sins and cosines up front.  I managed a few more
> "tricks" and knocked off 40% of the computation time:
>
> 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.
>
> Am I right in thinking that I wouldn't get much of a speedup by
> rewriting this in C as most of the time is spent in necessary python
> functions?

You would be able to get rid of the Python function call overhead of
rotation(), the ufunc machinery, and unnecessary array
creation/deletion. It could be worth your time experimenting with a
quick Cython implementation. That might help you (and the rest of us!)
answer this question instinctively the next time around.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
-- Umberto Eco
```