I'm trying to measure the angle between two points relative to the X-axis, in degrees.
From looking at other posts on stack overflow, I've been using the following code:
private double GetAngleBetweenTwoPoints(double x1, double y1, double x2, double y2)
{
return Math.Atan2(y2 - y1, x2 - x1) * 180.0 / Math.PI;
}
The problem is, this seems to work fine for some values, but not others. For instance, passing in (0, 0, 1, 1) correctly returns the value 45. However, passing in (0, 0, 2, 1) returns 26.565051177078 when I would expect 22.5.
What am I doing wrong?
The inverse tangent of 0.5 is 26.565 degrees, not 22.5 degrees.
You can see this by taking the tangent of 26.565 degrees, which gives a number very close to 0.5, whereas the tangent of 22.5 degrees is roughly 0.414.
(NB as tangent is cyclical, there are an infinite number of other values x
for which tan x
is 0.5, but that is not relevant for this question.)