close

How to know the angle between two vectors?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to know the angle between two vectors in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to know the angle between two vectors?

  1. How to know the angle between two vectors?

    Specifically for working with shapely linestring objects, assuming your object (two points) is of the form (min long, min lat, max long, max lat)

  2. know the angle between two vectors

    Specifically for working with shapely linestring objects, assuming your object (two points) is of the form (min long, min lat, max long, max lat)

Method 1

The tangent of the angle between two points is defined as delta y / delta x That is (y2 – y1)/(x2-x1). This means that math.atan2(dy, dx) give the angle between the two points assuming that you know the base axis that defines the co-ordinates.

Your gun is assumed to be the (0, 0) point of the axes in order to calculate the angle in radians. Once you have that angle, then you can use the angle for the remainder of your calculations.

Note that since the angle is in radians, you need to use the math.pi instead of 180 degrees within your code. Also your test for more than 360 degrees (2*math.pi) is not needed. The test for negative (< 0) is incorrect as you then force it to 0, which forces the target to be on the x axis in the positive direction.

Your code to calculate the angle between the gun and the target is thus

myradians = math.atan2(targetY-gunY, targetX-gunX)

If you want to convert radians to degrees

mydegrees = math.degrees(myradians)

To convert from degrees to radians

myradians = math.radians(mydegrees)

Python ATAN2

The Python ATAN2 function is one of the Python Math function which is used to returns the angle (in radians) from the X -Axis to the specified point (y, x).

math.atan2()

Definition Returns the tangent(y,x) in radius.

Syntax
math.atan2(y,x)

Parameters
y,x=numbers

Examples
The return is:

>>> import math  
>>> math.atan2(88,34)  
1.202100424136847  
>>>

Method 2

Specifically for working with shapely linestring objects, assuming your object (two points) is of the form (min long, min lat, max long, max lat)

from math import atan2,degrees
line = #Your-LineString-Object
lineList = list(line.coords)

def AngleBtw2Points(pointA, pointB):
  changeInX = pointB[0] - pointA[0]
  changeInY = pointB[1] - pointA[1]
  return degrees(atan2(changeInY,changeInX)) #remove degrees if you want your answer in radians

AngleBtw2Points(lineList[0],lineList[1]) 

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read