Search code examples
mathlanguage-agnostic

How to map angles from [0..360] to [-180..180]


I'm drawing a blank at the moment. I need to translate back and forth between "signed" and "unsigned" degrees, [-180..180] and [0..360]

The simple way to go from [-180..180] to [0..360] is

(d+360) % 360 // (+360 removes ambiguity about the sign in some languages).

How do I do the inverse operation? I can do

if d<180 d else d-360

but it looks ugly.

Edit: Here are some example numbers. I want to map this

[0, 90, 180, 270, 360]

to this:

[0, 90, 180, -90, 0]

Edit 2: OK, brain freeze is over. The answer is

(a+180)%360-180


Solution

  • OK, brain freeze over the answer is

    (a+180)%360-180