Home > Back-end >  Shortest distance between two degree marks on a circle in python
Shortest distance between two degree marks on a circle in python

Time:08-25

I'm attempting to calculate the distance between two-degree markings on a circle.

Here's the scenario.

I have angle 255 and need to move to 40 by continually increasing or reducing 255 by 0.5. I need to determine the shortest path between moving clockwise and anticlockwise prior to starting.

After finding the shortest path, I also need to decide whether to continuously increase or decrease angle 255 by 0.5 until I reach 40.

Can anyone help?

CodePudding user response:

a,b = max(a,b), min(a,b)
dist = min(a-b, b 360-a)

to get also direction:

if a > b:
    if a - b > b   360 - a:
        signeddist = b   360 - a  //positive
    else:
        signeddist = b - a  //negative
 else:
    if b - a > a   360 - b:
        signeddist = a   360 - b  //positive
    else:
        signeddist = a - b  //negative

Or this (assuming angles and result in radians):

rot_angle = atan2(sin(a-b), cos(a-b)) 
    

    

CodePudding user response:

There is quite a neat trick for this, which is to use the sign of the cross product to determine the direction.

If we map each angle to the unit vector in its direction and picture the unit vectors in the xy plane, then we could calculate the z component of the cross using something like

def cross(alpha: float, beta: float) -> float:
    return cos(alpha) * sin(beta) - sin(alpha) * cos(beta)

where alpha and beta are the start and end angles (in radian) respectively.

To determine the direction of the smallest turn, then, we can just check the sign of the z component of the cross product: if it's positive, add the increment; otherwise: subtract.

CodePudding user response:

def turningRTC(a, b):
    if a > b:
        if a - b > b   360 - a:
            a  = 0.5
        else:
            a -= 0.5
    else:
        if b - a > a   360 - b:
            a -= 0.5
        else:
            a  = 0.5
return a
  • Related