Eric - 6 months ago 126
Python Question

# Calculate angle (clockwise) between two points

I have been not using math for a long time and this should be a simple problem to solve.

Suppose I have two points A: (1, 0) and B: (1, -1).

I want to use a program (Python or whatever programming language) to calculate the clockwise angle between A, origin (0, 0) and B. It will be something like this:

``````angle_clockwise(point1, point2)
``````

Note that the order of the parameters matters. Since the angle calculation will be clockwise:

• If I call angle_clockwise(A, B), it returns 45.

• If I call angle_clockwise(B, A), it returns 315.

In other words, the algorithm is like this:

1. Draw a line (line 1) between the first point param with (0, 0).

2. Draw a line (line 2) between the second point param with (0, 0).

3. Revolve line 1 around (0, 0) clockwise until it overlaps line 2.

4. The angular distance line 1 traveled will be the returned angle.

Is there any way to code this problem?

Use the inner product and the determinant of the two vectors. This is really what you should understand if you want to understand how this works. You'll need to know/read about vector math to understand.

``````from math import acos
from math import sqrt
from math import pi

def length(v):
return sqrt(v[0]**2+v[1]**2)
def dot_product(v,w):
return v[0]*w[0]+v[1]*w[1]
def determinant(v,w):
return v[0]*w[1]-v[1]*w[0]
def inner_angle(v,w):
cosx=dot_product(v,w)/(length(v)*length(w))