在Java中将角度标准化为+/-π弧度的标准方法 [英] Standard way to normalize an angle to +/- π radians in Java
问题描述
在Java中是否存在库函数或众所周知的快速有效方法来将角度标准化为+/-π - 例如添加两个角度时?
Is there a library function or a well-known quick efficient way in Java to normalize an angle to +/- π — e.g. when adding two angles?
我现在得到了什么(基于这个回答)基本上是下面的代码......
What I've got now (based on this answer) is basically the code below...
private static final double TWO_PI = 2 * Math.PI;
double normalize(double theta) {
double normalized = theta % TWO_PI;
normalized = (normalized + TWO_PI) % TWO_PI;
return normalized <= Math.PI ? normalized : normalized - TWO_PI;
}
...但它似乎有点复杂,性能方面我是对模运算符不感兴趣。 (注意,我不能保证 theta
不是一些相对较大的数字,所以我认为没有循环的纯加法/减法解决方案。我不知道实际上知道手动循环可能与%
进行比较。)
...but it seems a little complicated and performance-wise I'm not excited about the modulo operator. (Note that I can't guarantee theta
isn't some relatively large number, so I don't think there's a pure addition/subtraction solution without looping. I don't actually know how a hand-rolled loop is likely to compare to %
.)
是否经过充分测试我可以使用优化的库函数,还是一个更好的算法,或者这样做得好吗?
Is there a well-tested optimized library function I can use, or a better algorithm, or is this as good as it gets?
推荐答案
Apache commons有一个:
Apache commons has one:
规范化-π之间的角度和+π
normalize an angle between -π and +π
a = MathUtils.normalizeAngle(a,0.0);
并且看一下源代码,你可以用它来重现它(它们使用自己的 FastMath.floor
但是如果你想在没有外部库的情况下这样做的话):
And looking at the source code, you could reproduce it with this (they use their own FastMath.floor
but in case you want to do it without an external library):
theta - TWO_PI * Math.floor((theta + Math.PI) / TWO_PI)
未来:此方法刚刚(2017年6月)已被删除来自最新的commons-math 4.x代码库。如果您在此之后使用的是某个版本,则需要使用 commons-numbers 相反(一旦发布) - 目前:
Note for readers from the future: this method has just (June 2017) been removed from the latest commons-math 4.x codebase. If you're using a version after this, you'll want to use commons-numbers instead (once it's released) - currently:
a = PlaneAngleRadians.normalizeBetweenMinusPiAndPi(a);
或
a = PlaneAngleRadians.normalize(a, 0.0);
这篇关于在Java中将角度标准化为+/-π弧度的标准方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!