Search code examples
pythonarraysvectorangledot-product

Dot Product and Angle in Degrees between two Numpy Arrays


I would like to write a function that takes two numpy arrays with the same length and returns:

  • the dot product of the two arrays
  • the angle between the two vectors in degrees

The expected output is as such:

print(angle_dot(np.array([0., 1.]), np.array([1., 0.])))
## (0.0, 90.0)

print(angle_dot(np.array([2., -1, 1, -2]), np.array([-1., 1.5, 3., 1])))
## (-2.5, 102.5)

This is what I have so far, I can't seem to get the value for the angle between the arrays correct.

import numpy as np
def angle_dot(a, b):
    dot_product = round(np.dot(a, b), 1)
    angle = round(np.degrees(dot_product), 1)
    return dot_product, angle

print(angle_dot(np.array([0., 1.]), np.array([1., 0.])))
## (0.0, 0.0)

print(angle_dot(np.array([2., -1, 1, -2]), np.array([-1., 1.5, 3., 1])))
## (-2.5, -143.2)

Solution

  • The angle is defined using this formula (this is just one way of defining it):

    cos(alpha) = (a . b) / (|a| * |b|)
    

    So, the angle is:

    alpha = arccos((a . b) / (|a| * |b|))
    

    Code:

    import numpy as np
    
    def angle_dot(a, b):
        dot_product = np.dot(a, b)
        prod_of_norms = np.linalg.norm(a) * np.linalg.norm(b)
        angle = round(np.degrees(np.arccos(dot_product / prod_of_norms)), 1)
        return round(dot_product, 1), angle
    
    print(angle_dot(np.array([0., 1.]), np.array([1., 0.])))
    
    print(angle_dot(np.array([2., -1, 1, -2]), np.array([-1., 1.5, 3., 1])))
    

    Output:

    (0.0, 90.0)
    (-2.5, 102.5)