Inconsistency with Math.Round()

后端 未结 3 809
孤独总比滥情好
孤独总比滥情好 2021-01-20 17:11

I have two functions that are intended to contain angles between (-180,180] and (-π,π]. The intent is that given any angle from -inf to +inf it will retain the equivalent an

3条回答
  •  盖世英雄少女心
    2021-01-20 17:39

    For the angle in degrees, if x is between -180 and 180, then 180 - x is between 0 and 360. What you want is equivalent to asking that 180 - x is between 0 (inclusive), and 360 (exclusive). So, as soon as 180 - x reaches 360, we want to add 360 to the angle. This gives us:

    return angle + 360d * Math.Floor((180d - angle) / 360d);
    

    Same thing for the angle in radians:

    return angle + twopi * Math.Floor((Math.PI - angle) / twopi);
    

提交回复
热议问题