language-agnosticgeometryangle

How can I find the smallest difference between two angles around a point?


Given a 2D circle with 2 angles in the range -PI -> PI around a coordinate, what is the value of the smallest angle between them?

Taking into account that the difference between PI and -PI is not 2 PI but zero.

An Example:

Imagine a circle, with 2 lines coming out from the center, there are 2 angles between those lines, the angle they make on the inside aka the smaller angle, and the angle they make on the outside, aka the bigger angle.

Both angles when added up make a full circle. Given that each angle can fit within a certain range, what is the smaller angles value, taking into account the rollover


Solution

  • This gives a signed angle for any angles:

    a = targetA - sourceA
    a = (a + 180) % 360 - 180
    

    Beware in many languages the modulo operation returns a value with the same sign as the dividend (like C, C++, C#, JavaScript, full list here). This requires a custom mod function like so:

    mod = (a, n) -> a - floor(a/n) * n
    

    Or so:

    mod = (a, n) -> (a % n + n) % n
    

    If angles are within [-180, 180] this also works:

    a = targetA - sourceA
    a += (a>180) ? -360 : (a<-180) ? 360 : 0
    

    In a more verbose way:

    a = targetA - sourceA
    a -= 360 if a > 180
    a += 360 if a < -180