Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The fastest way to get current quadrant of an angle

Firstly, this may sound very trivial, but currently I am creating a function getQuadrant(degree) for returning a quadrant from a given angle.

For instance, if degree is >= 0 and < 90, it will return 1. If degree is >= 90 and < 180, it will return 2. And so forth. This is very trivial. However, to be able to deal with degrees other than 0-360, I simply normalized those numbers to be in 0-360 degree range first, like this:

            while (angle > 360)
                angle = angle - 360;
            end

            while (angle < 0)
                angle = angle + 360;
            end

After that, I calculate. But to be frank, I hate using while statements like this. Are there other mathematical ways that can point out the quadrant of the angle in one go?

EDIT: I see that there are lots of good answers. Allow me to add "which algorithm will be the fastest?"

like image 425
Karl Avatar asked Dec 20 '12 15:12

Karl


People also ask

How do you find the reference angle for quadrant 1?

When the terminal side is in the first quadrant (angles from 0° to 90°), our reference angle is the same as our given angle. This makes sense, since all the angles in the first quadrant are less than 90°. So, if our given angle is 33°, then its reference angle is also 33°.

What is the formula to be used for solving the reference angle in quadrant IV?

For an angle in the fourth quadrant, the reference angle is 2π−t 2 π − t or 360∘−t 360 ∘ − t . If an angle is less than 0 or greater than 2π , add or subtract 2π as many times as needed to find an equivalent angle between 0 and 2π .


2 Answers

You can use the modulo operation:

angle %= 360.0; // [0..360) if angle is positive, (-360..0] if negative
if (angle < 0) angle += 360.0; // Back to [0..360)
quadrant = (angle/90) % 4 + 1; // Quadrant
like image 166
Vincent Mimoun-Prat Avatar answered Sep 23 '22 19:09

Vincent Mimoun-Prat


(angle/90)%4+1

Assumptions:

  1. angle is an integer
  2. angle is positive
  3. / is integer division

For negative angles you'll need some additional handling.

like image 24
maxim1000 Avatar answered Sep 22 '22 19:09

maxim1000