Getting the angle between two vectors is well known. But finding the ‘rotation angle’ from one vector to another needs a bit more consideration. The following functions can handle this.

import numpy as np

def calculate_rotation_angle_from_vector_to_vector(a,b):
""" return rotation angle from vector a to vector b, in degrees.

Args:
a : np.array vector. format (x,y)
b : np.array vector. format (x,y)

Returns:
angle [float]: degrees. 0~360
"""

unit_vector_1 = a / np.linalg.norm(a)
unit_vector_2 = b / np.linalg.norm(b)
dot_product = np.dot(unit_vector_1, unit_vector_2)
angle = np.arccos(dot_product)

angle = angle/ np.pi * 180

c = np.cross(b,a)

if c>0:
angle +=180

return angle

This function will use cross product between two vectors to identify if the rotation direction is CW or CCW. This function will return rotation angle in CCW direction in degrees.

Categories: python

#### Augusto de Lelis Araujo · March 27, 2022 at 10:53 pm

??????????????????????????????????????????????????????????
a = [1,0] and b = [1,0] >> angle = 0º
a = [1,-0.01] and b = [1,0] >> angle = 180.57293869768262º
??????????????????????????????????????????????????????????

#### Augusto de Lelis Araujo · March 27, 2022 at 11:20 pm

import numpy as np

u = [1.0, -0.01]
u = u / np.linalg.norm(u)

v = [1.0, 0.0] # vector fixed (reference)
dot_product = np.dot(u, v)

angle = np.arccos(dot_product) / np.pi * 180

if (u[1] >= 0.0):
angle = angle

if (u[1] < 0.0):
angle = 360 – angle

print(str(angle) + 'º')