Search code examples
mathgeometryangle

Map angles to a 0-1 range


Let's say you have two angles, and you label them 0 and 1. Then you have another angle x. You also know if you'll be going Clockwise or Counter Clockwise to get from angle 0 to angle 1. How do you calculate a number that can describe that third angle?

Examples:

Angle at 0 Angle at 1 Rotation Direction Target Angle Mapped number (x)
90° CCW 60° 2/3
90° CW 60° 1/3
180° CW 90° 1.5
180° CCW 90° 0.5

Problems I'm having:

  • When x can't be supported within 0 and 1 (I am fine with it just telling me it couldn't do it, but having the number would be cooler).
  • When switching from Counter-Clock-Wise (CCW) to CW.

Solution

  • Check the next approach:

    def ratio(x, a, b, dircw = False):
        if dircw:
            if x > a:
                x -= 360
            if b > a:
                b -= 360
        else:
            if b < a:
                b += 360
            if x < a:
                x += 360
    
        return (x-a)/(b-a)
    
    
    print(ratio(60, 0, 90))
    print(ratio(60, 0, 90, True))
    print(ratio(60, 90, 0, True))
    print(ratio(90, 0, 180, True))
    print(ratio(90, 0, 180))
    
    0.6666666666666666
    1.1111111111111112
    0.3333333333333333
    1.5
    0.5
    

    We consider solution of linear equation (solve inverse of linear interpolation)

    x = a*(1-t) + b*t
    

    for unknown t.

    We have to make normalization to provide b after a in cyclic manner in both directions - so b+- correction.

    To get only positive results, we normalize also x.