I was trying to calculate the angle between two points using

math.atan2(y, x)

as was suggested in numerous forums and tutorials. After trying it myself, it didn't quite work as charmingly as it did for others. So I made a simple example of what it does and I need some help figuring out why it does it and how to fix it:

import math

p1 = (0.0, 0.0)
p2 = (1.0, 1.0)

dx = p1[0] - p2[0]
dy = p1[1] - p2[1]

angle = math.atan2(dy, dx)
angle = math.degrees(angle)

print(angle)

This should obviously give a 45° angle as a result, right? Instead, it gives me a -135° angle, so it's 180° off. What I suspected was that it begins from the left hand side of a full circle and the angle increases clockwise instead of counter-clockwise like it should. After testing this I found out this was indeed the case. It's as if it calculates off a mirror image of the usual angle. Is there any way to fix this?

(I'm running Python 3.2.2 if that helps)

In your example, x == y == -1.0. The vector (-1.0, -1.0) makes an angle of -135.0 degrees with the horizontal axis, and not 45.0 degrees. So math.atan2() is correct.

Or reverse your vector:

import math

p1 = (0.0, 0.0)
p2 = (1.0, 1.0)

# use vector from p2 to p1
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]

angle = math.atan2(dy, dx)
angle = math.degrees(angle)

print(angle)  # 45.0

But what if I use variables for the points? How could I make sure it always gives a correct angle? I tried using abs(x) but it divides the circle into 4 90° sectors, whereas I would like to have a full circle.

With degree(atan2(dy, dx)), you get an angle between -180 and 180 degrees. If you want to forget the direction information, you can use degree(atan2(dy, dx)) % 180.0 . It will give an angle between 0 and 180 degrees.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.