class Point:
def __init__(self, x: int, y: int):
self.x: int = x
self.y: int = y
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).
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 a 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
expects:
45
225
CodePudding user response:
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)))