Skip to content

Instantly share code, notes, and snippets.

@Lingnik
Created July 24, 2015 07:35
Show Gist options
  • Save Lingnik/c66819b659c160746822 to your computer and use it in GitHub Desktop.
Save Lingnik/c66819b659c160746822 to your computer and use it in GitHub Desktop.
n-dimensional angles in python
import numpy as np
def unit_vector(vector):
""" Returns the unit vector of the vector. """
return vector / np.linalg.norm(vector)
def angle_between(vector_1, vector_2):
""" Returns the angle in radians between vectors 'vector_1' and 'vector_2'::
>>> 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
"""
vector_1_u = unit_vector(vector_1)
vector_2_u = unit_vector(vector_2)
angle = np.arccos(np.dot(vector_1_u, vector_2_u))
if np.isnan(angle):
if (vector_1_u == vector_2_u).all():
return 0.0
else:
return np.pi
return angle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment