Q:

Finding the cos of an angle in java

I was asked to find the cos following this equation:
I was able to find the sin of the angle, however when finding the cos, the number I would get is quite different from the correct value:
I used the following code for finding the cos.
ps: I can't use math.cos

public static double cos(double x, int n){

    // declaring cos and factorial

    double cos = 0.0;

    // this loop determines how long does the loop go so the answer is more accurate
    for (long howlong = 1 ; howlong <=n; howlong++){
        double factorial =1;

    // this will calculate the factorial for even numbers ex/ 2*2 = 4 , 4-2 = 2
    // for the denominator 

    for (int factorialnumber=1; factorialnumber<=2*howlong-2; factorialnumber++){
        factorial = factorial * howlong;    

    }

    // now we need to create the pattern for the + and -
    // so we use % that switches the sign everytime i increments by 1

    if (howlong%2==1){
        cos = cos + (double) (Math.pow(x, 2*howlong-2)/factorial);
    }

    else{
        cos = cos - (double) (Math.pow(x, 2*howlong-2)/factorial);
    }
    }
    return cos;
}

edit: I figured out my mistake as it was multiplying the factorial by how long instead of factorial number.

A:

You have two bugs.
(Bug 1) Where you wrote 
factorial = factorial * howlong;

it should have been
factorial = factorial * factorialnumber;

(Bug 2) You're not resetting your factorials on each iteration through the outer loop.  So you need to move the line 
double factorial =1;

down a couple of lines, so that it's inside the outer loop.
If you make those two changes, then the result of cos(Math.PI / 6, 10) is 0.8660254037844386 which seems correct to me.

