Skip to content

Instantly share code, notes, and snippets.

@Alex7Li
Last active January 29, 2022 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alex7Li/f9eed631c76febc161f6eb042ed71993 to your computer and use it in GitHub Desktop.
Save Alex7Li/f9eed631c76febc161f6eb042ed71993 to your computer and use it in GitHub Desktop.
Rotate
import math
import numpy as np
def get_rotating_transform(u, v):
"""
Given two unit vectors u, v,
we compute the rotation R such that v = R @ u
"""
assert np.isclose(np.linalg.norm(u), 1)
assert np.isclose(np.linalg.norm(v), 1)
n = np.cross(u, v)
while np.allclose(n, 0): # u and v are on the same line -.-
rand_dir = np.random.randn(3)
n = np.cross(u, rand_dir)
n /= np.linalg.norm(n)
t = np.cross(n, u)
T = np.stack([u, t, n], axis=1)
alpha = math.atan2(v @ t, v @ u)
R = np.array([
[math.cos(alpha), -math.sin(alpha), 0],
[math.sin(alpha), math.cos(alpha), 0],
[0, 0, 1]
])
transform = T @ R @ T.T
assert np.allclose(v, transform @ u)
return transform
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment