6

Can I find a specific function in Numpy or Scipy to generate a random N dimensional rotation matrix (or orthogonal matrix)? I need to move a vector on an ND sphere to another random point on this sphere.

孙文趋
  • 577
  • 6
  • 13
  • 1
    are you asking the math to construct a ND rotational matrix or do you know the math and asking for writing the program? – Eular Jun 09 '16 at 14:06
  • 1
    I wanted to ask how to generate a random nd rotational matrix, because I need to do the importance sampling on an nd sphere. – 孙文趋 Jun 09 '16 at 15:44
  • Quick'n'dirty: Produce a general random matrix, with entries in [-1,1] and apply the QR decomposition. The Q factor is then a random orthogonal matrix (to be a rotation matrix, the determinant has to be 1, but det(Q) depends on the dimension). However, there is no guarantee to uniformity relative to the Haar measure. – Lutz Lehmann Jun 09 '16 at 21:13
  • 7
    What you are looking for is `scipy.stats.special_ortho_group`. I don't have the privilege to reopen the question to answer it, so I'm abusing the comment here. This is not a timely answer, and you've probably figured it out the hard way. Hopefully, people in the future don't need to suffer from that. –  May 21 '19 at 01:24
  • You want `scipy.stats.special_ortho_group`; It's build in to scipy and will sample random rotation matrices in any number of dimensions. This is not a duplicate of https://stackoverflow.com/q/38426349/900749 since it asks for rotation, rather than orthonormal, although this answer https://stackoverflow.com/a/55289807/900749 is the correct one. – MRule Jul 04 '22 at 16:32

1 Answers1

6

https://math.stackexchange.com/questions/442418/random-generation-of-rotation-matrices

This may answer your question, at least as far as the strategy goes. As far as I know, there is no standard or library function from numpy that will do precisely what you need. A myriad of computational strategies are presented there, but I would prefer an extension of the quaternion approach since it can preserve a uniform distribution, which is what I'm assuming you're after.

EDIT: My original answer stated "roughly uniform," whereas after a bit more research I found that the quaternion approach, when sampled from a uniform distribution, will in fact preserve a uniform distribution in the rotations.

Community
  • 1
  • 1
gankoji
  • 853
  • 1
  • 10
  • 23
  • 2
    In terms of a programming question, the simplest and most idiomatic way to do this now is `scipy.stats.special_ortho_group.rvs(NDIMS)` (https://stackoverflow.com/a/55289807/900749). In the interest of keeping stack overflow a current and useful knowledge-base, one may want to update this answer (and re-open the question, it is clear and should not have been closed). – MRule Jul 04 '22 at 16:34