# Efficiently rotate vector in 2D (and 3D)

I need to efficiently rotate a 2D (and 3D) vector in a CUDA kernel. I was thinking about generating random unitary rotation matrices. I don't need to know the angle, it just has to be randomly distributed.

Is there some clever way to avoid the computational complexity of the division and the square root for the norm? Or another way to rotate a vector?

I need this for a 2D GPU off-lattice Monte-Carlo simulation, but a 3D solution would be nice too.

Thanks in advance.

• en.wikipedia.org/wiki/Fast_inverse_square_root – spektr Apr 14 '16 at 17:02
• Are the vectors to be "randomly" rotated based at the origin? If you want to achieve a specific distribution, say a uniform distribution, then it would be helpful to Readers to see your implementation using "the division and the square root" before they try to offer an equivalent that avoids these. – hardmath Apr 15 '16 at 2:34
• I want to represent hard shape molecules, I have two characteristic vectors: r (position vector) and u (normalized orientation vector). The shape of the molecules is generated by applying matrix transformations on these vectors. I want to rotate the molecule, with uniform probability, around r, which is the origin for u. – iko Apr 15 '16 at 15:17

## 1 Answer

Some of the standard methods for random rotations in 3D (Sphere Point Picking) are listed on Mathworld. On a CPU, Marsaglia's method is quite efficient, because it avoids expensive $\sin$ and $\cos$ computations.

Marsaglia's method isn't really suitable for a GPU, because it sometimes rejects pairs of random numbers. If you have access to fast trigonometric functions, the approach of equation (6) to (8) at the page linked above probably works better.

Circle point picking in 2D is simpler. In any case, I don't think you can avoid the computation of a vector norm / square root, which is often implemented in hardware nowadays. Drawing random numbers or computing trigonometric functions is probably significantly more expensive.