Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should trigonometric functions be cached?

How extensive are functions like Math.sin(), Math.cos() etc.? Does the compiler optimise the code if you call the method with the same arguments multiple times in a row? If not, at how many calls of these methods should you start caching the result in a variable?

like image 624
MyNameIsHans Avatar asked Oct 23 '25 19:10

MyNameIsHans


1 Answers

The trigonometric functions are usually implemented as Taylor expansions. They are fast. You can write your own and compare.

public class Main{
    private static double factorial(double n) {
        if (n <= 1) // base case
            return 1;
        else
            return n * factorial(n - 1);
    }
    private static double sin(int n) {
        int PRECISION = 10;
        double rad = n*1./180.*Math.PI;
        double sum = rad;
        for (int i = 1; i <= PRECISION; i++) {
            if (i % 2 == 0)
                sum += Math.pow(rad, 2*i+1) / factorial(2 * i + 1);
            else
                sum -= Math.pow(rad, 2*i+1) / factorial(2 * i + 1);
        }
        return sum;
    }

    public static void main(String []args){
        System.out.println(sin(180));
        System.out.println(Math.sin(Math.PI));

        System.out.println(sin(90));
        System.out.println(Math.sin(Math.PI/2));

        System.out.println(sin(200));
        System.out.println(Math.sin(200*2*Math.PI/360));
    }
}

Surely you can cache the values but these methods are likely to be already optimized.

like image 199
Niklas Rosencrantz Avatar answered Oct 26 '25 09:10

Niklas Rosencrantz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!