Easy way to keeping angles between -179 and 180 degrees

后端 未结 16 2703
长发绾君心
长发绾君心 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]]]
    

提交回复
热议问题