旋转坐标变换中的numpy巨大误差

时间:2015-03-20 12:03:56

标签: python numpy matrix coordinate-transformation

我想通过旋转在欧几里得空间中进行坐标转换。我想通过找到将当前z轴与给定输入向量对齐的矩阵来做到这一点。此时这些旋转不会产生令人满意的输出。

import numpy as np

vec_in = np.array([1*np.tan(np.pi/180*45), 1*np.tan(np.pi/180*45), 1]) 
vec_in /= np.linalg.norm(vec_in) #normalize, so we can use np.dot as scalar product
print vec_in

#find angles between vec_in and our x and y axis
#avoid inverse trigonometric functions, thereby increase accuracy
cosx = np.dot(vec_in, np.array([1,0,0]))
sinx = np.sqrt(1-cosx**2) 
cosy = np.dot(vec_in, np.array([0,1,0]))
siny = np.sqrt(1-cosy**2)

#turn around z to bring x fraction to zero
Rz = np.array([[cosx,-sinx,0], [sinx,cosx,0], [0,0,1]])
Rzi = np.linalg.inv(Rz)
print 'accuracy Rz\n', np.dot(Rz, Rzi)

#turn around y to align z to vector
Ry = np.array([[cosy,0,siny], [0,1,0], [-siny,0,cosy]])
Ryi = np.linalg.inv(Ry)
print 'accuracy Ry\n', np.dot(Ry, Ryi)

print np.dot(Ryi, np.dot(Rzi, vec_in)), '\tshould be [1,0,0]'
print np.dot(Rz, np.dot(Ry ,[0,0,1])), '\tshould be', vec_in

输出是:

[ 0.57735027  0.57735027  0.57735027]
accuracy Rz
[[  1.00000000e+00   5.55111512e-17   0.00000000e+00]
 [  0.00000000e+00   1.00000000e+00   0.00000000e+00]
 [  0.00000000e+00   0.00000000e+00   1.00000000e+00]]
accuracy Ry
[[  1.00000000e+00   0.00000000e+00  -7.70426082e-17]
 [  0.00000000e+00   1.00000000e+00   0.00000000e+00]
 [  0.00000000e+00   0.00000000e+00   1.00000000e+00]]
[-0.0067889  -0.13807119  0.99039904]   should be [1,0,0]
[ 0.47140452  0.66666667  0.57735027]   should be [ 0.57735027  0.57735027  0.57735027]

np.dot(Rx,Rxi)我现在得出结论,逆矩阵运作良好;只是实际的结果完全不像我期望的那样。为什么?我怎么能得到我想要的东西?

1 个答案:

答案 0 :(得分:4)

你必须先围绕y轴旋转矢量,使它位于xy平面上,我称之为v1。没有规范化,v1应该是[sqrt(2),1,0]。 (占cosysiny

然后旋转v1使其也位于xz平面上。所以它在x轴上。

import numpy as np

vec_in = np.array([1*np.tan(np.pi/180*45), 1*np.tan(np.pi/180*45), 1]) 
vec_in /= np.linalg.norm(vec_in) #normalize, so we can use np.dot as scalar product
print vec_in

#find angles between vec_in and our x and y axis
#avoid inverse trigonometric functions, thereby increase accuracy

cosy = vec_in[0]/np.sqrt((vec_in[2]**2+vec_in[0]**2)) 
siny = np.sqrt(1-cosy**2)

#turn around y to align z to vector
Ry = np.array([[cosy,0,siny], [0,1,0], [-siny,0,cosy]])
Ryi = np.linalg.inv(Ry)
print 'accuracy Ry\n', np.dot(Ry, Ryi)

v1 = Ry.dot(vec_in) #z = 0
cosx = v1[0]/np.sqrt((v1[1]**2+v1[0]**2)) 
sinx = np.sqrt(1-cosx**2)

#turn around z to bring x fraction to zero
Rz = np.array([[cosx,-sinx,0], [sinx,cosx,0], [0,0,1]])
Rzi = np.linalg.inv(Rz)
print 'accuracy Rz\n', np.dot(Rz, Rzi)


print np.dot(Rzi, np.dot(Ry, vec_in)), '\tshould be [1,0,0]'