Standard way to normalize an angle to +/- π radians in Java

后端 未结 2 655
一整个雨季
一整个雨季 2021-01-04 05:00

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 th

2条回答
  •  长发绾君心
    2021-01-04 05:20

    Apache commons has one:

    http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/util/MathUtils.html#normalizeAngle(double, double)

    normalize an angle between -π and +π

    a = MathUtils.normalizeAngle(a, 0.0);

    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)
    

    Source is here: https://github.com/apache/commons-math/blob/53ec46ba272e23c0c96ada42f26f4e70e96f3115/src/main/java/org/apache/commons/math4/util/MathUtils.java#L107


    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);
    

    or

    a = PlaneAngleRadians.normalize(a, 0.0);
    

提交回复
热议问题