Search code examples
ctrigonometrytaylor-series

This code of taylor series doesn't work for n= 1 or anything other than 0. Why?


First of all, let me tell you, I am learning programming.

Today, I tried to find the approximate value of cosine by using the taylor series. When I put n=0, my code gives me correct result of 1. But when I put n=1 or anything else, my code does not give correct result.

I am unable to understand where the problem is. Can anyone help?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{
    float xnot = atof(argv[1]);
    float n = atof(argv[2]);
    float cosine = cos(xnot*(3.14159265/180));
    float result;
    printf("%.4f\n", cosine);
    float min;


    float d, c, b;
    c = 1;
    d = 2 * n; 
    for(b = 1; b <= d; b++){
        c = c * b; /*value of the factorial is in c*/
    }
    c = c;
    float power;
    power = pow((-1), n);
    xnot = pow(xnot, 2*n);


    for(min = 0; min <= n; min++)
    {

        result += ((power * xnot) / c);
    }
    printf("%.4f", result);
}

Solution

  • You need to redo all calculations inside the for-loop. Keeping as much as your original code as possible, it could be something like:

    int n = atoi(argv[2]);  // n is an integer
    ...
    ...
    float result = 1;  // The first term (n=0) gives 1
    
    for(int i = 1; i <= n; i++)   // Start the loop from 1
    {
        float d, c, b;
        c = 1;
        d = 2 * i;     // Use i instead of n
        for(b = 1; b <= d; b++){
            c = c * b; /*value of the factorial is in c*/
        }
        float power;
        power = pow((-1), i);    // Use i instead of n
        xnot = pow(xnot, 2*i);   // Use i instead of n
    
        result += ((power * xnot) / c);
    }
    

    The code can be optimized - both for performance and precision - but as already stated I tried to keep it close to your original code.