Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)
I need to identify the angles between two n-dimensional vectors in Python. For example, Input can be two lists like the following: [1,2,3,4] and [6,7,8,9].

1 Answer

0 votes
by (36.8k points)

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.

If you are a beginner and want to know more about Data Science the do check out the Data Science course

Browse Categories

...