矛盾与Math.Round() [英] Inconsistency with Math.Round()
问题描述
我有意欲包含(-180,180]和(-π,π]之间的角度两个功能。这样做的目的是,鉴于任何角度从-inf至+ INF它将保留在指定的时间间隔的等效角度。例如,对于1550°的夹角为110°。
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 angle in the intervals specified. For example the angle for 1550° is 110°.
public double WrapBetween180(double angle)
{
return angle - 360d * Math.Round(angle / 360d, MidpointRounding.AwayFromZero);
}
public double WrapBetweenPI(double angle)
{
const double twopi = 2d * Math.PI;
return angle - twopi * Math.Round(angle / twopi, MidpointRounding.AwayFromZero);
}
这将产生以下结果。
WrapBetween180(-180) = -180
WrapBetween180( 180) = 180
WrapBetweenPI(-Math.PI) = Math.PI
WrapBetweenPI( Math.PI) = -Math.PI
其中没有一个是我想要的是什么,我想的是:
none of which is what I want. What I wanted is:
WrapBetween180(-180) = 180
WrapBetween180( 180) = 180
WrapBetweenPI(-Math.PI) = Math.PI
WrapBetweenPI( Math.PI) = Math.PI
我tryied用四舍五入的方法打转转,但仍不能得到理想的结果。问题是明显的,因为有时我处理角度大约只有接近-π或π和我得到的不连续性是我的结果。
I tryied playing around with the rounding methods, but still cannot get the desired results. The problem is pronounced because sometimes the angles I deal with are only approximately close to -π or π and I am getting discontinuities it my results.
如何最好的任何建议与非包容性的下限和包容性的高限执行角度包装功能?
Any suggestions on how to best implement angle wrapping functions with non-inclusive low limit and inclusive high limits?
推荐答案
有关在度的角度,如果 X
为-180到180,然后之间 180 - X
为360介于0和你想要什么就相当于问这个 180 - X
介于0(含)和360(不含)。因此,只要 180 - X
达到360,我们要添加360的角度。这给了我们:
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);
这篇关于矛盾与Math.Round()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!