codemachine98
codemachine98

Reputation: 251

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 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)

Upvotes: 0

Views: 2562

Answers (2)

Djaouad
Djaouad

Reputation: 22776

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)

Upvotes: 1

James
James

Reputation: 36608

The formula for finding the angle between 2 n-dimensional arrays using the dot product is:

dot(a, b) = ||a|| * ||b|| * cos(theta)
theta = arccos( dot(a, b) / (||a|| * ||b||))

Or in numpy:

def angle(a, b):
    return np.degrees(np.arccos(np.dot(a, b)/ (np.linalg.norm(a) * np.linalg.norm(b))))

Upvotes: 1

Related Questions