Charith
Charith

Reputation: 445

Angle between two vectors in the interval [0,360]

I'm trying to find the angle between two vectors.
Following is the code that I use to evaluate the angle between vectors ba and bc

import numpy as np
import scipy.linalg as la

a = np.array([6,0])
b = np.array([0,0])
c = np.array([1,1])

ba = a - b
bc = c - b

cosine_angle = np.dot(ba, bc) / (la.norm(ba) * la.norm(bc))
angle = np.arccos(cosine_angle)

print (np.degrees(angle))

My question is,
here in this code:
for both c = np.array([1,1]) and c = np.array([1,-1]) you get 45 degrees as the answer. I can understand this in a mathematical viewpoint because, from the dot product you always focus on the angle in the interval [0,180].

But geometrically this is misleading as the point c is in two different locations for [1,1] and [1,-1].
So is there a way that I can get the angle in the interval [0,360] for a general starting point
b = np.array([x,y])

Appreciate your help

Upvotes: 6

Views: 3054

Answers (1)

amzon-ex
amzon-ex

Reputation: 1744

Conceptually, obtaining the angle between two vectors using the dot product is perfectly alright. However, since the angle between two vectors is invariant upon translation/rotation of the coordinate system, we can find the angle subtended by each vector to the positive direction of the x-axis and subtract one value from the other.

The advantage is, we'll use np.arctan2to find the angles, which returns angles in the range [-π,π] and hence you get an idea of the quadrant your vector lies in.

# Syntax: np.arctan2(y, x) - put the y value first!
# Instead of explicitly referring by indices, you can unpack each vector in reverse, like so:
# np.arctan2(*bc[::-1])

angle = np.arctan2(bc[1], bc[0]) - np.arctan2(ba[1], ba[0])

Which you can then appropriately transform to get a value within [0, 2π].

Upvotes: 5

Related Questions