Working on code to calculate cosine with factorial sum


I have been struggling with this code and just do not seem to grasp what I am doing wrong.

The code is suppose to calculate : Sum of a series of "Cosine" with pattern [(-1)^i(x)^2i]/(2i)!

pattern

Here is my code thus far:

#include <stdio.h>
#include <math.h>

float factorial(int n){
    if (n==0)
        return 1;
    else
        return 2*n*factorial(n-1);
}

int main (){
    float i, n;
    float sum=0;
    printf("Enter desired interger: ");
    scanf("%f", &n);

    for (i=0; i<=1; i++) 
        sum = sum + (pow(-1,i)*pow(n,2*i))/(factorial(n));

    printf("The value is %f\n", sum);
    return 0;
}

I still working on it, any info or help will be much appreciated!

edit:

Just fixed it guys, this is new format I had to use for my professor:

#include <stdio.h>
#include <math.h>
int factorial(int n)
{
if (n==0) return 1;
else
return n*factorial(n-1);
}
float mycos(float x)
{
float sum=0;
int i;
for (i=0;i<=10;i++) sum = sum + (pow(-1,i)*pow(x,2*i))/factorial(2*i);
return sum;
}
int main()
{
int i=1;
printf("     x    mycos(x)   cos(x)\n");
for (i=1;i<=10;i++)
printf(" %f %f %f\n", i*.1, mycos(i*.1), cos(i*.1));
return 0;
}

Thank you all for your explanations, they helped out Immensely!


Answers:


One thing I see, is that your for loop within main only runs through 2 real iterations, once for i == 0, and again for i == 1.

For the taylor expansion to work fairly effectively, it needs to be run through more sequence terms (more loop iterations).

another thing I see, is that your denominator is the n! rather than (2 * n)!

For efficiency, I might also implement the factorial routine as follows:

unsigned int factorial(int n){
    unsigned int product = 1;

    for(int I = 1; I <= n; I++) product *= I;

    return product;
}

The above factorial routine is for a more EXACT factorial calculation, which perhaps you don't need for this purpose. For your purposes, perhaps the floating point variant might be good enough.

float factorial(int n){
    float product = 1;

    for(int I = 1; I <= n; I++) product *= (float)I;

    return product;
}

I should also note why I am stating to perform factorial in this manner. In general a loop construct will be more efficient than its recursive counterpart. Your current implementation is recursive, and thus the implementation I provide SHOULD be quite a bit more efficient from both performance, and memory utilization.