Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4477961

java.lang.Math.toDegrees(double) could be optimized



    • b33
    • x86
    • windows_2000



        Name: bsC130419 Date: 07/09/2001

        java version "1.3.0"
        Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.0-C)
        Java HotSpot(TM) Client VM (build 1.3.0-C, mixed mode)

        The source code for java.lang.Math.toDegrees(double) is as follows:

            public static double toDegrees(double angrad) {
        return angrad * 180.0 / PI;

        Notice that the expression 180.0 / PI is effectively a constant. However,
        because Java performs calculations from left to right, the multiplication is
        performed first, and then the division is performed. This could be optimized
        by enclosing 180.0 / PI in parenthesis as follows:

            public static double toDegrees(double angrad) {
        return angrad * (180.0 / PI);

        The compiler and/or hotspot will recognize the result of the division as a
        constant and only calculate it once. This avoids an expensive division
        operation for each call to toDegrees().

        However, one caveat is that this may affect the results of some calculations.
        For example, some range of numbers that used to overflow to infinity by
        performing the multiplication by 180, will now not overflow and will return a
        valid result. As well, by pre-computing 180.0/PI, we may affect the precision
        of the result. In my tests, however, the result was identical and is 350%
        faster with the parenthesis.

        The same issue exists in java.lang.StrictMath.toDegrees(double).

        Along the same lines, java.lang.Math.toRadians(double) is implemented as

            public static double toRadians(double angdeg) {
        return angdeg / 180.0 * PI;

        This could be reworked for better performance as follows:

            public static double toRadians(double angdeg) {
        return angdeg * (PI / 180.0);

        This performs the division only once (probably at compile-time). Each call to
        toRadians() now only has to perform one multiplication instead of a division
        AND multiplication before. In my tests, this change also had a 350% increase
        in performance without affecting the results.

        The same issue exists with java.lang.StrictMath.toRadians().
        (Review ID: 127319)
        ###@###.### 2004-11-11 22:25:06 GMT


          Issue Links



                bpb Brian Burkhalter
                bstrathesunw Bill Strathearn (Inactive)
                0 Vote for this issue
                3 Start watching this issue