Smallest angle to turn

442 Views Asked by At

I have a an object that starts an arbitrary heading in degrees. This object will rotate about an angle to reach a target heading. To reach this target heading, you can rotate about two different angles and end up with the same heading.

I am looking for a fast method, that finds the smaller of the two angles.

For instance, you start at $0^\circ$ and then you rotate negative $270.5^\circ$, your heading will be the same, as if you had rotated positive $90.5^\circ$.

I am looking for the angle with the smaller magnitude ($90.5^\circ$ in the example).

How would I do this? Also, this approach has to be able to work with all headings including non-whole integers (floats) and modulus operator cannot be used in this approach because % only works with whole integers and floating point mod is not available. I am looking for an approach that is trig based (doesn't have to be).

So... I have an approach that works only for headings with a magnitude less than or equal to $360^\circ$

$\text{shortest angle} = \arccos ( \cos x^\circ)\times \arcsin ( \sin x^\circ )$

Is there another way... Maybe something with $\arctan2$...

2

There are 2 best solutions below

0
On

Depending on what formulas are available
$x-360*(round(x/360))$
$x-360*floor((x+180)/360))$

0
On

Given an angle x, you want another angle $y\in (-180,180]$ which is equivalent mod 360. One way to do this is (as you guessed) $y=arctan2(sin(x),cos(x))$. This is not necessarily the fastest way, though, as trig functions can be relatively expensive operations. If you're programming in a low level language, a faster way is to use a few basic arithmetic operations to make your own ``mod 360'' operation, like:

z = x-360*floor(x/360)
if z>180:
    y=z-360
else:
    y=z