Search code examples
rmathgeometryangle

Ensure an angle is between 0 and 360 degree


I want to ensure the angle h_ur is between 0 to 360 degrees.

  h_ur <- atan2(b, a)*(180.0/pi)

but for the sake of the question, I have simplified h_ur as following:

h_ur <- -5
if (h_ur > 360){
  h <- h_ur - 360
} else if (h_ur < 0){
  h <- 360 + h_ur
} else {
  h <- h_ur
}
print(h)

However, this code would only work if the h_ur is between 720 and 360, and 0 and -360.

  • How can I alter the code to ensure it would work even if h_ur is outside this range?
  • Is there a more elegant way to do this?

Solution

  • I would just us modular arithmetic. Below returns 0 to 0, 359.999 to 359.999 and 360 to 0 if that is what you want.

    h_ur <- c(-180,-5,0,90,359.999, 360,720,865)
    h <- h_ur %% 360
    print(h)
    
    > print(h)
    [1] 180.000 355.000   0.000  90.000 359.999   0.000   0.000 145.000