orlp - 1 year ago 108

C# Question

In a programming language (Python, C#, etc) I need to determine how to calculate the angle between a line and the horizontal axis?

I think an image describes best what I want:

Given (P1_{x},P1_{y}) and (P2_{x},P2_{y}) what is the best way to calculate this angle? The origin is in the topleft and only the positive quadrant is used.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

First find the difference between the start point and the end point.

```
deltaY = P2_y - P1_y
deltaX = P2_x - P1_x
```

Then calculate the angle.

```
angleInDegrees = arctan(deltaY / deltaX) * 180 / PI
```

If your language includes an `atan2`

function it becomes the following instead:

```
angleInDegrees = atan2(deltaY, deltaX) * 180 / PI
```

**An implementation in Python using radians (provided by Eric Leschinski, who edited my answer):**

```
from math import *
def angle_trunc(a):
while a < 0.0:
a += pi * 2
return a
def getAngleBetweenPoints(x_orig, y_orig, x_landmark, y_landmark):
deltaY = y_landmark - y_orig
deltaX = x_landmark - x_orig
return angle_trunc(atan2(deltaY, deltaX))
angle = getAngleBetweenPoints(5, 2, 1,4)
assert angle >= 0, "angle must be >= 0"
angle = getAngleBetweenPoints(1, 1, 2, 1)
assert angle == 0, "expecting angle to be 0"
angle = getAngleBetweenPoints(2, 1, 1, 1)
assert abs(pi - angle) <= 0.01, "expecting angle to be pi, it is: " + str(angle)
angle = getAngleBetweenPoints(2, 1, 2, 3)
assert abs(angle - pi/2) <= 0.01, "expecting angle to be pi/2, it is: " + str(angle)
angle = getAngleBetweenPoints(2, 1, 2, 0)
assert abs(angle - (pi+pi/2)) <= 0.01, "expecting angle to be pi+pi/2, it is: " + str(angle)
angle = getAngleBetweenPoints(1, 1, 2, 2)
assert abs(angle - (pi/4)) <= 0.01, "expecting angle to be pi/4, it is: " + str(angle)
angle = getAngleBetweenPoints(-1, -1, -2, -2)
assert abs(angle - (pi+pi/4)) <= 0.01, "expecting angle to be pi+pi/4, it is: " + str(angle)
angle = getAngleBetweenPoints(-1, -1, -1, 2)
assert abs(angle - (pi/2)) <= 0.01, "expecting angle to be pi/2, it is: " + str(angle)
```

All tests pass. See https://en.wikipedia.org/wiki/Unit_circle

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**