#NEWLINE# def random_rot( dim ) : #NEWLINE# #INDENT# "Return a random rotation matrix, drawn from the Haar distribution\n    (the only uniform distribution on SO(n)).\n    The algorithm is described in the paper\n    Stewart, G.W., 'The efficient generation of random orthogonal\n    matrices with an application to condition estimators', SIAM Journal\n    on Numerical Analysis, 17(3), pp. 403-409, 1980.\n    For more information see\n    http://en.wikipedia.org/wiki/Orthogonal_matrix#Randomization" #NEWLINE# H = eye ( dim ) #NEWLINE# D = ones ( ( dim , ) ) #NEWLINE# for n in range ( 1 , dim ) : #NEWLINE# #INDENT# x = normal ( size = ( ( ( dim - n ) + 1 ) , ) ) #NEWLINE# D [ ( n - 1 ) ] = sign ( x [ 0 ] ) #NEWLINE# x [ 0 ] -= ( D [ ( n - 1 ) ] * sqrt ( ( x * x ) . sum ( ) ) ) #NEWLINE# Hx = ( eye ( ( ( dim - n ) + 1 ) ) - ( ( 2.0 * outer ( x , x ) ) / ( x * x ) . sum ( ) ) ) #NEWLINE# mat = eye ( dim ) #NEWLINE# mat [ ( n - 1 ) : , ( n - 1 ) : ] = D #NEWLINE# H = dot ( H , mat ) #NEWLINE# #UNINDENT# D [ ( - 1 ) ] = ( - D . prod ( ) ) #NEWLINE# H = ( D * H . T ) . T #NEWLINE# return H