Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angles between two n-dimensional vectors in Python

I need to determine the angle(s) between two n-dimensional vectors in Python. For example, the input can be two lists like the following: [1,2,3,4] and [6,7,8,9].

like image 640
Peter Avatar asked May 13 '10 14:05

Peter


People also ask

How do you find the angle between 2D vectors?

To calculate the angle between two vectors in a 2D space: Find the dot product of the vectors. Divide the dot product by the magnitude of the first vector. Divide the resultant by the magnitude of the second vector.

How do you find the angle in Python?

angle() function is used when we want to compute the angle of the complex argument. A complex number is represented by “ x + yi ” where x and y are real number and i= (-1)^1/2 . The angle is calculated by the formula tan-1(x/y).


2 Answers

Note: all of the other answers here will fail if the two vectors have either the same direction (ex, (1, 0, 0), (1, 0, 0)) or opposite directions (ex, (-1, 0, 0), (1, 0, 0)).

Here is a function which will correctly handle these cases:

import numpy as np  def unit_vector(vector):     """ Returns the unit vector of the vector.  """     return vector / np.linalg.norm(vector)  def angle_between(v1, v2):     """ Returns the angle in radians between vectors 'v1' and 'v2'::              >>> angle_between((1, 0, 0), (0, 1, 0))             1.5707963267948966             >>> angle_between((1, 0, 0), (1, 0, 0))             0.0             >>> angle_between((1, 0, 0), (-1, 0, 0))             3.141592653589793     """     v1_u = unit_vector(v1)     v2_u = unit_vector(v2)     return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) 
like image 186
David Wolever Avatar answered Oct 05 '22 23:10

David Wolever


import math  def dotproduct(v1, v2):   return sum((a*b) for a, b in zip(v1, v2))  def length(v):   return math.sqrt(dotproduct(v, v))  def angle(v1, v2):   return math.acos(dotproduct(v1, v2) / (length(v1) * length(v2))) 

Note: this will fail when the vectors have either the same or the opposite direction. The correct implementation is here: https://stackoverflow.com/a/13849249/71522

like image 34
Alex Martelli Avatar answered Oct 05 '22 22:10

Alex Martelli