【问题标题】:Ensure an angle is between 0 and 360 degreeEnsure an angle is between 0 and 360 degree
【发布时间】:2022-12-02 00:54:15
【问题描述】:

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?

【问题讨论】:

    标签: r math geometry angle


    【解决方案1】:

    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
    

    【讨论】:

      【解决方案2】:

      I believe the range of atan2 is in radians: -π <= t <= +π. Plan accordingly. Use modular arithmetic. You'll need to transform negative values by adding 2*π

      【讨论】:

        猜你喜欢
        • 2022-12-01
        • 2020-02-28
        • 2022-12-02
        • 2021-03-15
        • 1970-01-01
        • 2019-03-11
        • 1970-01-01
        • 2023-03-25
        • 2022-12-26
        相关资源
        最近更新 更多