diff --git a/src/java/org/apache/commons/math/util/MathUtils.java b/src/java/org/apache/commons/math/util/MathUtils.java index d354b870c..6d8f4ae16 100644 --- a/src/java/org/apache/commons/math/util/MathUtils.java +++ b/src/java/org/apache/commons/math/util/MathUtils.java @@ -43,6 +43,9 @@ public final class MathUtils { /** 0.0 cast as a short. */ private static final short ZS = (short)0; + /** 2 π. */ + private static final double TWO_PI = 2 * Math.PI; + /** * Private Constructor */ @@ -705,6 +708,28 @@ public final class MathUtils { } + /** + * Normalize an angle in a 2&pi wide interval around a center value. + *

This method has three main uses:

+ * + *

Note that due to numerical accuracy and since π cannot be represented + * exactly, the result interval is closed, it cannot be half-closed + * as would be more satisfactory in a purely mathematical view.

+ * @param a angle to normalize + * @param center center of the desired 2π interval for the result + * @return a-2kπ with integer k and center-π <= a-2kπ <= center+π + */ + public static double normalizeAngle(double a, double center) { + return a - TWO_PI * Math.floor((a + Math.PI - center) / TWO_PI); + } + /** * Round the given value to the specified number of decimal places. The * value is rounded using the {@link BigDecimal#ROUND_HALF_UP} method. @@ -1007,4 +1032,5 @@ public final class MathUtils { } return ret; } + } diff --git a/src/site/xdoc/changes.xml b/src/site/xdoc/changes.xml index c1190ca5b..47b4792a6 100644 --- a/src/site/xdoc/changes.xml +++ b/src/site/xdoc/changes.xml @@ -146,6 +146,10 @@ Commons Math Release Notes Added a equals and hash methods in MathUtils to check for double arrays + + Added an angle normalization method in MathUtils to force angles in some + user-defined interval +