The fastest way to get the current quadrant of an angle

Firstly, this may seem very trivial, but I'm currently creating a getQuadrant (degree) function to return a quadrant with a given angle.

For example, if degree> = 0 and <90, it will return 1. If degree> = 90 and <180, it will return 2. And so on. This is very trivial. However, to deal with degrees other than 0-360, I simply normalized these numbers in the range of 0-360 degrees, for example:

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

After that I calculate. But honestly, I hate using such statements. Are there other mathematical methods that can point to the quadrant of an angle at a time?

EDIT: I see that there are many good answers. Let me add, " which algorithm will be the fastest? "

+7
source share
4 answers

Take advantage of integer arithmetic:

 angle = angle - (angle/360)*360; if (angle < 0) angle = angle + 360; 

The idea is that since angle/360 rounded down ( floor() ), (angle/360) gives you k you need to do alpha = beta + 360k .

The second line is normalized from [-359, -1] to [1.359], if necessary.

+3
source

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 
+4
source
 (angle/90)%4+1 

Assumptions:

  • angle is an integer
  • angle is positive
  • / - integer division

For negative angles you will need additional processing.

+2
source

You noted the trigonometry of your question, so here is the trigonometry:

a) accept sin(theta) and cos(theta) - it does not matter how many (positive or negative) multiples of 360ยฐ included; sin(400ยฐ)==sin(40ยฐ)==sin(-320ยฐ) , etc.

b) if sin(theta)>0 and cos(theta)>0 theta is in quadrant 1

if sin(theta)>0 and cos(theta)<0 theta is in quadrant 2

and so on around the clock. Oh, and decide what to do in 4 corners , where sin and cos return 0 .

+1
source

All Articles