Find angle from two points formula

4.9k views Asked by At

I have question about the formula to calculate the Angle between two points p1(x1,y1), p2(x2,y2).

I use this formula :

angle = arctan(y2-y1/x2-x1)

Can you explain, why y2,y1 and x2,x1 must be subtracted ?

Thanks

2

There are 2 answers

5
bunbun On BEST ANSWER

tan, sin, and cos are actually measuring the ratios between two edges of a 3-edged object aka a triangle.

Hence in your case, to form that triangle, you will need the lengths of two edges. They are the lengths between y1 and y2, and x1 and x2.

That is why you deduct y1 from y2 and x1 from x2.

In fact, you have to ensure that the signs are correct too, else you will get a different angle as your answer.

0
Alex Taylor On

According to Wikipedia's article on inverse trigonometric functions (which includes the arctangent function), they are 'used to obtain an angle from any of the angle's trigonometric ratios' i.e. the y-component compared to the x-component of the vector you're looking at. Your vector starts at (x1, y1) so subtracting those components from second point effectively centers the vector at (0, 0), then dividing the y-component by the x-component will give you the trigonometric ratio (aka gradient in this case) that can be passed through the arctan function to get the angle.

On an implementation note, you will want to use an arctan2 function to prevent a divide-by-zero error in the case of a vertical line. A vertical line has an infinite gradient which computers don't deal with. The arctan2 function will accept the x and y components separately, side stepping the issue. See the documentation for Java or Python for example.