Working on code to calculate cosine with factorial sum

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.

Leave a Comment