python三维空间实现A向量绕B向量 旋转45度
- User
python三维空间实现A向量绕B向量 旋转45度
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
python三维空间实现A向量绕B向量 旋转45度
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
假设 A 向量为 (ax, ay, az),B 向量为 (bx, by, bz),则 A 向量绕 B 向量旋转 45 度的过程可以分为以下几步:
首先需要计算旋转轴和旋转角度。可以通过向量叉乘和点乘来计算:
具体代码如下:
import math
A = [1, 2, 3] B = [4, 5, 6]
A_norm = [i / math.sqrt(sum([j2 for j in A])) for i in A] B_norm = [i / math.sqrt(sum([j2 for j in B])) for i in B]
rot_axis = [A_norm[1]*B_norm[2]-A_norm[2]*B_norm[1], A_norm[2]*B_norm[0]-A_norm[0]*B_norm[2], A_norm[0]*B_norm[1]-A_norm[1]*B_norm[0]]
angle = math.acos(sum([i*j for i,j in zip(A_norm, B_norm)])) rot_angle = angle * 45 / math.pi
接下来需要根据旋转轴和旋转角度构造出旋转矩阵。
旋转矩阵分为绕 X 轴旋转、绕 Y 轴旋转和绕 Z 轴旋转三种情况。由于旋转轴不一定与 X/Y/Z 轴平行,因此需要先将旋转轴旋转至 X/Y/Z 轴平面上,再进行旋转。具体步骤如下:
最终得到的旋转矩阵可以用 3x3 的 NumPy 数组表示:
import numpy as np
theta1 = math.atan2(rot_axis[0], math.sqrt(rot_axis[1]**2 + rot_axis[2]**2)) cos_theta1 = math.cos(theta1) sin_theta1 = math.sin(theta1)
R1 = np.array([[cos_theta1, 0, sin_theta1], [0, 1, 0], [-sin_theta1, 0, cos_theta1]])
proj = np.array([rot_axis[0], rot_axis[1], 0]) theta2 = math.atan2(proj[1], proj[0]) cos_theta2 = math.cos(theta2) sin_theta2 = math.sin(theta2)
R2 = np.array([[cos_theta2, -sin_theta2, 0], [sin_theta2, cos_theta2, 0], [0, 0, 1]])
cos_rot = math.cos(rot_angle) sin_rot = math.sin(rot_angle)
R3 = np.array([[1, 0, 0], [0, cos_rot, -sin_rot], [0, sin_rot, cos_rot]])
rot_mat = R1 @ R2 @ R3
最后将 A 向量乘上旋转矩阵就可以得到旋转后的 A 向量了:
rotated_A = rot_mat @ A
完整代码如下:
import math import numpy as np
A = [1, 2, 3] B = [4, 5, 6]
A_norm = [i / math.sqrt(sum([j2 for j in A])) for i in A] B_norm = [i / math.sqrt(sum([j2 for j in B])) for i in B]
rot_axis = [A_norm[1]*B_norm[2]-A_norm[2]*B_norm[1], A_norm[2]*B_norm[0]-A_norm[0]*B_norm[2], A_norm[0]*B_norm[1]-A_norm[1]*B_norm[0]]
angle = math.acos(sum([i*j for i,j in zip(A_norm, B_norm)])) rot_angle = angle * 45 / math.pi
theta1 = math.atan2(rot_axis[0], math.sqrt(rot_axis[1]**2 + rot_axis[2]**2)) cos_theta1 = math.cos(theta1) sin_theta1 = math.sin(theta1)
R1 = np.array([[cos_theta1, 0, sin_theta1], [0, 1, 0], [-sin_theta1, 0, cos_theta1]])
proj = np.array([rot_axis[0], rot_axis[1], 0]) theta2 = math.atan2(proj[1], proj[0]) cos_theta2 = math.cos(theta2) sin_theta2 = math.sin(theta2)
R2 = np.array([[cos_theta2, -sin_theta2, 0], [sin_theta2, cos_theta2, 0], [0, 0, 1]])
cos_rot = math.cos(rot_angle) sin_rot = math.sin(rot_angle)
R3 = np.array([[1, 0, 0], [0, cos_rot, -sin_rot], [0, sin_rot, cos_rot]])
rot_mat = R1 @ R2 @ R3
rotated_A = rot_mat @ A
print(rotated_A) # [2.07806408 2.61071603 2.81577499]