Easy way to keeping angles between -179 and 180 degrees

后端 未结 16 2673
长发绾君心
长发绾君心 2020-12-04 16:41

Is there an easy way to convert an angle (in degrees) to be between -179 and 180? I\'m sure I could use mod (%) and some if statements, but it gets ugly:


/         


        
16条回答
  •  情歌与酒
    2020-12-04 17:15

    I don't know much Java, but I came across the same problem in Python. Most of the answers here were either for integers so I figured I'd add one that allows for floats.

    def half_angle(degree):
        return -((180 - degree) % 360) + 180
    

    Based off the other answers I'm guessing the function would looks something like this in Java (feel free to correct me)

    int halfAngle(int degree) {
        return -Math.floorMod(180 - degree, 360) + 180
    }
    
    double halfAngle(double degree) {
        // Java doesn't have a built-in modulus operator
        // And Math.floorMod only works on integers and longs
        // But we can use ((x%n) + n)%n to obtain the modulus for float
        return -(((180 - degree) % 360 + 360) % 360) + 180
    }
    

    Replace int with float to your liking.

    This works for any degree, both positive and negative and floats and integers:

    half_angle(180) == 180
    half_angle(180.1) == -179.9  // actually -179.89999999999998
    half_angle(-179.9) == -179.9
    half_angle(-180) = 180
    half_angle(1) = 1
    half_angle(0) = 0
    half_angle(-1) = -1
    

    Math explanation:

    Because the modulo operator is open at the upper end, the value x % 360 is in the range [0, 360), so by using the negative angle, the upper end becomes the lower end. So -(-x%360) is in (-360, 0], and -(-x%360)+360 is in (0, 360].

    Shifting this by 180 gives us the answer.

提交回复
热议问题