Eric - 1 year ago 357

Python Question

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:

- Draw a line (line 1) between the first point param with (0, 0).
- Draw a line (line 2) between the second point param with (0, 0).
- Revolve line 1 around (0, 0) clockwise until it overlaps line 2.
- The angular distance line 1 traveled will be the returned angle.

Is there any way to code this problem?

Answer Source

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.

See: https://en.wikipedia.org/wiki/Dot_product and https://en.wikipedia.org/wiki/Determinant

```
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))
rad=acos(cosx) # in radians
return rad*180/pi # returns degrees
def angle_clockwise(A, B):
inner=inner_angle(A,B)
det = determinant(A,B)
if det<0: #this is a quality of the det. If the det < 0 then B is clockwise of A
return inner
else: # if the det > 0 then A is immediately clockwise of B
return 360-inner
```

In the determinant computation, you're concatenating the two vectors to form a 2 x 2 matrix, for which you're computing the determinant.