Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clockwise angle between two line

I want to calculate a clockwise angle between two line segment A and B. So the resulting angle must be between 0 to 360-1 degrees. I've seen all other answers in SO but they gave me negative angles. Thanks.

like image 862
VOX Avatar asked Apr 25 '26 02:04

VOX


2 Answers

For turning any angle into a 0-359 range in C#, you can use the following "algorithm":

public int Normalise (int degrees) {
    int retval = degrees % 360;
    if (retval < 0)
        retval += 360;
    return retval;
}

C# follows the same rules as C and C++ and i % 360 will give you a value between -359 and 359 for any integer, then the second line is to ensure it's in the range 0 through 359 inclusive.

A sneaky version on one line:

    degrees = ((degrees % 360) + 360) % 360;

which would normalise it under all conditions. I'm not sure I'd worry too much about using the inline one-liner unless performance was critical, but I will explain it.

From degrees % 360, you will get a number between -359 and 359. Adding 360 will modify the range to between 1 and 729. Then the final % 360 will bring it back to the range 0 through 359.

like image 108
paxdiablo Avatar answered Apr 27 '26 16:04

paxdiablo


I would try :

if degrees is between [-360, 360]
    degrees = (degrees + 360) % 360;
else degrees = (degrees % 360) + 360) % 360;
like image 42
andrea Avatar answered Apr 27 '26 14:04

andrea