Easy way to keeping angles between -179 and 180 degrees

后端 未结 16 2653
长发绾君心
长发绾君心 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:25

    Here is my contribution. It seems to work for all angles with no edge issues. It is fast. It can do n180[360000359] = -1 almost instantaneously. Notice how the Sign function helps select the correct logic path and allows the same code to be used for different angles.

    Ratch

    n180[a_] := 
     If[Abs[Mod[a, If[Sign[a] == 0, 360, Sign[a] 360]]] <= 180, 
      Mod[a, If[Sign[a] == 0, 360, Sign[a] 360]], 
      Mod[a, If[Sign[a] == 0, 360, -Sign[a] 360]]]
    
    0 讨论(0)
  • 2020-12-04 17:29

    Maybe not helpful, but I always liked using non-degree angles.

    An angle range from 0 to 255 can be kept in bounds using bitwise operations, or for a single byte variable, simple allowed to overflow.

    An angle range from -128 to 127 isn't quite so easy with bitwise ops, but again, for a single-byte variable, you can let it overflow.

    I thought it was a great idea many years back for games, where you're probably using a lookup table for angles. These days, not so good - the angles are used differently, and are float anyway.

    Still - maybe worth a mention.

    0 讨论(0)
  • 2020-12-04 17:30

    I have made a formula for orientation of circular values

    to keep angle between 0 and 359 is:

    angle + Math.ceil( -angle / 360 ) * 360
    

    but to keep between -179 to 180 formula can be:

    angle + Math.ceil( (-angle-179) / 360 ) * 360
    

    this will give its orientation shift about -179 keeping actual angle intact

    generalized formula for shifting angle orientation can be:

    angle + Math.ceil( (-angle+shift) / 360 ) * 360
    
    0 讨论(0)
  • 2020-12-04 17:32
    // reduce the angle  
    angle =  angle % 360; 
    
    // force it to be the positive remainder, so that 0 <= angle < 360  
    angle = (angle + 360) % 360;  
    
    // force into the minimum absolute value residue class, so that -180 < angle <= 180  
    if (angle > 180)  
        angle -= 360;  
    
    0 讨论(0)
提交回复
热议问题