Python 2 + NumPy,163个字节
感谢xnor指出使用正态分布随机值,而不是统一值。
from numpy import*
n=input()
Q=random.randn(n,n)
for i in range(n):
for j in range(i):u=Q[:,j];Q[:,i]-=u*dot(u,Q[:,i])/dot(u,u)
Q/=(Q**2).sum(axis=0)**0.5
print Q
在具有高斯随机值的矩阵上使用Gram Schmidt正交化以具有所有方向。
演示代码后跟
print dot(Q.transpose(),Q)
n = 3:
[[-0.2555327 0.89398324 0.36809917]
[-0.55727299 0.17492767 -0.81169398]
[ 0.79003155 0.41254608 -0.45349298]]
[[ 1.00000000e+00 0.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 1.00000000e+00 -5.55111512e-17]
[ 0.00000000e+00 -5.55111512e-17 1.00000000e+00]]
n = 5:
[[-0.63470728 0.41984536 0.41569193 0.25708079 0.42659843]
[-0.36418389 0.06244462 -0.82734663 -0.24066123 0.3479231 ]
[ 0.07863783 0.7048799 0.08914089 -0.64230492 -0.27651168]
[ 0.67691426 0.33798442 -0.05984083 0.17555011 0.62702062]
[-0.01095148 -0.45688226 0.36217501 -0.65773717 0.47681205]]
[[ 1.00000000e+00 1.73472348e-16 5.37764278e-17 4.68375339e-17
-2.23779328e-16]
[ 1.73472348e-16 1.00000000e+00 1.38777878e-16 3.33066907e-16
-6.38378239e-16]
[ 5.37764278e-17 1.38777878e-16 1.00000000e+00 1.38777878e-16
1.11022302e-16]
[ 4.68375339e-17 3.33066907e-16 1.38777878e-16 1.00000000e+00
5.55111512e-16]
[ -2.23779328e-16 -6.38378239e-16 1.11022302e-16 5.55111512e-16
1.00000000e+00]]
在n = 50的瞬间完成,而在n = 500的瞬间完成。