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

Chris Colbert sccolbert@gmail....
Tue Mar 3 23:58:36 CST 2009

```since you only need to calculate the sine or cosine of a single value (not
an array of values) I would recommend using the sine and cosine function of
the python standard math library as it is a full order of magnitude faster.
(at least on my core 2 windows vista box)

i.e. import math as m

m.sin
m.cos

etc....

again, this is microoptimization.... a difference of 10^-5s per call vs
10^-6s per call numpy vs math

Chris

On Wed, Mar 4, 2009 at 12:11 AM, <josef.pktd@gmail.com> wrote:

> On Tue, Mar 3, 2009 at 11:41 PM, 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.
>
> 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.
>
> e.g. npcos = np.cos
> or I think the usual: `from numpy import cos, sin, zeros` should be
> better for speed
>
> also you still have a few duplicate multiplications, e.g. cx*cz, cx*sz, ..?
> but this looks already like micro optimization.
>
> Josef
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20090304/32925c0e/attachment.html
```