Home > Software design >  Why are my cos(x) outputs out of bound 1 and -1?
Why are my cos(x) outputs out of bound 1 and -1?

Time:11-03

My task is to implement the cos(x) function withou using Math. library and with the taylor polynom, my code looks like this:


public class Cosinus {
    public static void main(String[] args) {

        /*if(args.length == 0){
            System.out.println("ERROR: Geben Sie ein Argument für x ein!");
            return;
        }*/
        double x = 5;

        double summand1     = (x*x) / 2;
        double summand2     = (x*x*x*x) / (2*3*4);
        double summand3     = (x*x*x*x*x*x) / (2*3*4*5*6);
        double summand4     = (x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8);
        double summand5     = (x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10);
        double summand6     = (x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12);
        double summand7     = (x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14);
        //double summand8     = (x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14*15*16);
        //double summand9     = (x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18);
        //double summand10    = (x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x) / (2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18*19*20);
        

        double cosinusFunktion = (((((((1 - summand1)   summand2) - summand3)   summand4) - summand5)   summand6) - summand7);
        
        System.out.println(cosinusFunktion);
    }
}

For x = 1, 2, 3, and 4 Y is between 1 and -1 but with x = 5 it goes too -4 and if the x are even getting bigger this continues too 1287918274.

I cant solve this task but tthe task says it is enough to implement this funktion iwth the taylor polynom and the first 11 summand. I tried this too, but then even with x = 1 the bounds are broken. How can i solve this, so x = 42.5 is in bound of -1 and 1?

Tried more summands to make the result more excact, but the bounds get broken even more. tried implement the periodicity of x-2*PI, but I dont know where to put it and results get messed up eeven more.

CodePudding user response:

The Taylor expansion will always blow up for larger inputs. However, since:

sin(x) = sin(x   n*2*pi)  // for any integer n

You can simply pre-process you input with a modulus function to prevent your output from blowing up.

CodePudding user response:

you are getting an integer overflow for the factorial in the summand7 line

as a simple fix you can change the line to:

double summand7     = (x*x*x*x*x*x*x*x*x*x*x*x*x*x) / ((double) 2*3*4*5*6*7*8*9*10*11*12*13*14);
  • Related