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;
}
...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?