Search code examples
mathatan2

how to map atan2() to only positive radian?


atan2(y, x) has that discontinuity at PI (180°) where it switches to -PI..0 (-180°..0°) going clockwise.

if i apply the solution from this

// rust
(y.atan2(x).to_degrees() + 360.0) % 360.0

doesn't quite work with radians

(y.atan2(x) + PI*2.0) % PI*2.0 // doesn't give the right output most of the times

i am probably doing it wrong, cause i am not good at math

so what am i missing?


Solution

  • The problem is that the modulo operator and multiplication have the same precedence, and are left-associative, so your last expression is equivalent to

    ((y.atan2(x) + PI*2.0) % PI) * 2.0
    

    If you put parentheses around the second PI*2.0, it should work:

    (y.atan2(x) + PI*2.0) % (PI*2.0)