Python中3D坐标双旋转矩阵代码异常问题排查求助
旋转矩阵代码问题排查
我想要编写代码对包含3个原始坐标的矩阵执行两次旋转操作:先将R_x矩阵与原始矩阵相乘,再将R_z矩阵与第一次相乘的结果相乘。我编写了如下代码,但该代码无法匹配给定的测试数据,请问我的代码是否存在错误?
import numpy as np print("Enter the three coordinates in a single line (separated by space): ") entries = list(map(float, input().split())) original_matrix = np.array(entries).reshape(3, 1) theta = np.radians(float(input("insert theta in degrees: "))) R_x = np.array([[1,0,0],[0,np.cos(theta),-np.sin(theta)],[0,np.sin(theta),np.cos(theta)]]) R_z = np.array([[np.cos(theta),-np.sin(theta),0],[np.sin(theta),np.cos(theta),0],[0,0,1]]) prime_matrix = R_x.dot(original_matrix) d_prime_matrix = R_z.dot(prime_matrix) print("final coordinates are:") print(d_prime_matrix)
测试数据
- 旋转前坐标:

- 旋转后坐标:

代码错误分析
你的代码存在两个核心问题,导致无法匹配测试数据:
- 复用了同一个旋转角度:两次旋转(绕X轴、绕Z轴)是独立操作,应该对应不同的角度参数,但你只用了一个
theta同时初始化R_x和R_z,不符合测试场景的需求。 - 未确认旋转方向匹配性:标准旋转矩阵是右手坐标系下绕轴逆时针旋转(从轴正方向看向原点),如果测试数据中的旋转是顺时针方向,矩阵内的
sin符号需要反转(比如R_x中的-np.sin(theta)改为np.sin(theta),np.sin(theta)改为-np.sin(theta))。
修正示例代码
import numpy as np print("Enter the three coordinates in a single line (separated by space): ") entries = list(map(float, input().split())) original_matrix = np.array(entries).reshape(3, 1) # 分别输入两次旋转的角度 theta_x = np.radians(float(input("insert theta for X-axis rotation (degrees): "))) theta_z = np.radians(float(input("insert theta for Z-axis rotation (degrees): "))) # 绕X轴旋转矩阵(右手系逆时针) R_x = np.array([[1, 0, 0], [0, np.cos(theta_x), -np.sin(theta_x)], [0, np.sin(theta_x), np.cos(theta_x)]]) # 绕Z轴旋转矩阵(右手系逆时针) R_z = np.array([[np.cos(theta_z), -np.sin(theta_z), 0], [np.sin(theta_z), np.cos(theta_z), 0], [0, 0, 1]]) # 按顺序执行旋转:先X轴,再Z轴 prime_matrix = R_x.dot(original_matrix) d_prime_matrix = R_z.dot(prime_matrix) print("final coordinates are:") print(d_prime_matrix)
内容的提问来源于stack exchange,提问作者Amirhoseïn Amini
相关产品推荐
相关产品推荐

