Algorithm to rotate a float value between 0 and 360 degrees by +180 degrees

165 Views Asked by At

I want to take a floating point number (which will be between 0.0 and 360.0) and rotate that value by + 180 degrees.

So 0.0 would become 180.0

90.0 would become 270.0

180.0 would become 0.0

270 would become 90.0

I am thinking of the following algorithm, but it seems a bit crude? Is there a simpler way?:

If number < 180 then add 180 else if number > 180 then subtract 180.

2

There are 2 best solutions below

0
MBo On
(number + 180) % 360

Modulo operation for integers, also works for floats in some languages (Python etc). There are also special functions like C++ fmod

0
fana On

I think "just code the your idea as is" is the simplest, and enough.
Depending on the language, for example writing like (X<180 ? X+180 : X-180) makes the code look simpler, but the meaning is the same.

I think, thinking some other less straightforward writing styles (e.g. X - 180 * ( (X>=180) - (X<180) ) ) or employing operator that may be unnecessary expensive (e.g. modulo), will be nonsense.