iter
iter

Reputation: 4313

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

Upvotes: 1

Views: 1482

Answers (2)

iter
iter

Reputation: 4313

OK, brain freeze over the answer is

(a+180)%360-180

Upvotes: 5

Isa&#237;
Isa&#237;

Reputation: 49

For mapping a interval to another interval, you can use a linear interpolation like

float map(float n, float x1, float x2, float y1, float y2)
{
    float m = (y2 - y1) / (x2 - x1);
    return y1 + m * (n - x1);
}

where x1 <= n <= x2, results a value between y1 and y2

Upvotes: -1

Related Questions