Search code examples
javatrigonometrytaylor-series

Taylor series - calculating sin(x) until 6 digits precision


I must calculate sin(x) with a Taylor's series, until the output has 6 decimal places. The argument is an angle. I didn't implement checking the decimal places, I'm just printing next values (to check if it's working), but after 10-20 iteration it shows infinities/NaN's.

What's wrong in my thinking?

public static void sin(double x){
    double sin = 0;
    int n=1;
    while(1<2){

        sin += (Math.pow(-1,n) / factorial(2*n+1)) * Math.pow(x, 2*n+1);
        n++;

        try {
            Thread.sleep(50);
        } catch (InterruptedException ex) {

        }

        // CHECKING THE PRECISION HERE LATER
        System.out.println(sin);
    }
}

the Equation:

enter image description here


Solution

  • Don't compute each term using factorials and powers! You will rapidly overflow. Just realize that each next term is -term * x * x / ((n+1)*(n+2)) where n increases by 2 for each term:

    double tolerance = 0.0000007; // or whatever limit you want
    double sin = 0.;
    int n = 1;
    double term = x;
    while ( Math.abs(term) > tolerance ) {
      sin += term;
      term *= -( (x/(n+1)) * (x/(n+2)) );
      n+= 2;
    }