Math.toRadians is implemented like this:
public static double toRadians(double angdeg) {
return angdeg / 180.0 * PI;
}
1) If there is a difference, it's negligible. Math.toRadians does the division first, while that answer does the multiplication first.
2) The only way to find out for sure is to test it, but I would expect that neither is faster since they both do the same thing.
Answer from Stack Exchange Broke The Law on Stack OverflowMath.toRadians is implemented like this:
public static double toRadians(double angdeg) {
return angdeg / 180.0 * PI;
}
1) If there is a difference, it's negligible. Math.toRadians does the division first, while that answer does the multiplication first.
2) The only way to find out for sure is to test it, but I would expect that neither is faster since they both do the same thing.
In Java 9, the implementations of toRadians and toDegrees were changed to this:
public static double toRadians(double angdeg) {
return angdeg * DEGREES_TO_RADIANS;
}
public static double toDegrees(double angrad) {
return angrad * RADIANS_TO_DEGREES;
}
where DEGREES_TO_RADIANS and RADIANS_TO_DEGREES are literal constants. According to the following sources, this gives a 3-fold performance increase in a JMH micro-benchmark.
(We can also infer that the JIT compiler is not performing an optimization that is equivalent to the above. I presume that is because such an optimization could alter the computation's results. That would make it incorrect in general. The JIT compiler probably cannot make the judgement which way gives more accurate results, and it certainly cannot judge if accuracy ... or reproducibility ... is the most important criterion.)
The JDK bug database entries that relate to this are:
- https://bugs.openjdk.java.net/browse/JDK-8051808
- https://bugs.openjdk.java.net/browse/JDK-4477961
In summary, the answer for Java 9 and later is that the standard Math functions are faster than the alternative version. (Whether this was true in Java 8 and earlier is still untested ...)