# Calculate Angle Between Two Vectors In Python

In this tutorial, you will learn how to find the angle between two vectors using Python. After the end of this tutorial, you will able to calculate the angle between two dimensional or three-dimensional vectors. We will calculate the angle using some predefined method of math module.

Here, is a brief description of how to calculate the

## Mathematical Way Of Calculating The Angle Between Two Vectors

We can calculate the angle between two vectors by the formula, which states that the angle of two vectors cosθ is equal to the dot product of two vectors divided by the dot product of the mod of two vectors.

cosθ = ** A**.**B**/|**A**|.|**B**| =>θ = ** cos^-1 A**.**B**/|**A**|.|**B**|

**A**,** B** are two vectors and θ is the angle between two vectors** A** and **B**.

Example: Assume that we have two vectors** A**={8,6} and** B**={7,9}. Find the angle.

Solution: ** A**.**B** = 8*7+6*9 = 110

|**A**| = √ 8^2 +6^2 = 10

|**B**| = √ 7^2 +9^2 = 11.40

cosθ = 110/10*11.40 = **0.96**

θ= 16.26°

## Python Program To Calculate The Angle Between Two Vectors

Here, we use the ‘math’ module to calculate some complicated task for us like square root, cos inverse and degree using the functions **sqrt()**, **acos()**, **degrees()**.

This program helps us to find the angle between two-dimensional vectors. You can simply modify it for three-dimensional vectors.

import math a,b,c,d = input().split(" ") a,b,c,d=int(a),int(b),int(c),int(d)

Here, we input coordinates of two vectors ** A** and **B** where a,b are coordinates of vector **A** and c,d are of vector **B** and split by** split(“args= space”)** method. Next line converts all string **char** into **int** type.

def angle_of_vectors(a,b,c,d): dotProduct = a*c + b*d # for three dimensional simply add dotProduct = a*c + b*d + e*f modOfVector1 = math.sqrt( a*a + b*b)*math.sqrt(c*c + d*d) # for three dimensional simply add modOfVector = math.sqrt( a*a + b*b + e*e)*math.sqrt(c*c + d*d +f*f) angle = dotProduct/modOfVector1 print("Cosθ =",angle) angleInDegree = math.degrees(math.acos(angle)) print("θ =",angleInDegree,"°") angle_of_vectors(a,b,c,d)

In this section of program, we defined our method angle_of_vectors() with four arguments a,b,c,d. then we calculate the dot product of vectors (explained in the example) and mod of vectors. After that, we calculate the angle and first find cos^-1 of angle using acos() method and convert it into degree using** degrees()** method.

Input :

8 6 7 9

Output :

cos θ = 0.9647638212377322 θ = 15.255118703057764°

Also, read: How to Make Predictions with scikit-learn in Python

## Leave a Reply