Get angle that is out of a range

217 Views Asked by At

I would like to make a function that, given an angle and a range, obtains an angle that doesn't fall in the ranges $[0º, ±range]$ and $[180º, ±range]$.

I think that the following picture better explains the problem:

Problem image

If the input angle falls inside the red area, I need to return the nearest angle from the green area.

I need to support both clock- and counterclockwise (negative angles).

The following method does the trick for a range of 30º, but I'm sure that there is a better solution using trigonometric functions:

    internal static double GetAngleOutOfRange(double angle, double range)
    {
        if (angle >= 0 && angle <= 30)
            return 30;

        if (angle < 0 && angle >= -30)
            return -30;

        if (angle <= -150 && angle >= -180)
            return -150;

        if (angle >= 150 && angle <= 180)
            return 150;

        if (angle <= -180 && angle >= -210)
            return -210;

        if (angle >= 180 && angle <= 210)
            return 210;

        if (angle <= -330 && angle >= -360)
            return -330;

        if (angle >= 330 && angle <= 360)
            return 330;

        return angle;
    }

Thanks for your help.

2

There are 2 best solutions below

1
On BEST ANSWER

Working with sin and cos is indeed easier

s = sin( angle )

if |s| >= |sin( range )|  return angle

r = | range |
res = cos( angle ) < 0 ? 180-r : r

return s < 0 ? -res : +res

|x| is $|x|$ and cond ? a : b gives a if cond is true, b otherwise.

4
On

Assuming the output angle can just be in the range $(-180,180)$ and that the $range$ is in the interval $(0,90)$, here's some pseudo code that should work:

If $\; abs(\sin (angle)) < \sin (range) \;$ then
$\{$
$\quad $if $\cos(angle) \gt 0$ then
$\qquad angle=range$
$\quad $ else
$\qquad angle=180-range$

$\quad $if $\sin(angle) \lt 0$ then
$\qquad angle=-angle$
$\}$