Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find angle in degrees of a point from another point

#  Python 3.10 or above
class Point:
    def __init__(self, x: int, y: int):
        self.x: int = x  # x Coordinate
        self.y: int = y  # y Coordinate

I have two points A and B, where their x, y coordinate can be any integers (+ve/ 0/ -ve).
I want to find the angle in degree of one point from another.

For example, in this case we have points A(4,3) and B(6,5)

A.angleFromSelf(B) should get 45 (like this) and B.angleFromSelf(A) should get 225 (like this).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What is the best way of getting the angle in degrees of one point from another point?

I am thinking something like getting the slope of straight line AB, and then using the formula atan(slope) = angle, but I don’t know whether it works when there is negative slope.

tried:

from math import atan
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def angleFromSelf(self, other):
        slope = (self.y-other.y) / (self.x-other.x)
        angle = atan(slope)
        return angle

A = Point(4,3)
B = Point(6,5)

print(A.angleFromSelf(B))
print(B.angleFromSelf(A))

gets:

0.7853981633974483
0.7853981633974483

expect:

45
225

>Solution :

You need to use atan2 to get the correct result

from math import atan2, pi
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def angleFromSelf(self, other):
        angle = atan2(self.y-other.y, self.x-other.x)
        if angle<0:
            angle+=2*pi
        return angle

def rad_2_deg(angle):
    return angle*180/pi

A = Point(4,3)
B = Point(6,5)

print(rad_2_deg(A.angleFromSelf(B)))
print(rad_2_deg(B.angleFromSelf(A)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading