cmathtrigonometrylogic-error

Taylor series expansion of cos(x) is not working


#include <stdio.h>
#include <math.h>
#define PI 3.1416
double fact(n){
  double x = 1;
  for(int i = 1 ; i <= n ; i++){
    x = x*i;
  }
  return x;
}
int main(void) {
  int deg,term,n=1,sign=1;
  float radian,result=0;
  printf("Enter the Angle (in degree) : ");
  scanf("%d",&deg);
  printf("Enter the number of terms : ");
  scanf("%d",&term);
  radian = deg*(PI/180.0);

  for(int count = 0 ;n<=term ; count+=2){
    result = result + sign *(double)(pow(radian,count)/fact(count));
    n++;
    sign = sign * (-1) ;
  }
  
  printf("user defined cos(%d) = %f\n",deg,result);
  printf("inbuilt cos(%d) = %f\n",deg,cos(deg));
  return 0;
}

I tried similar code with sin function and with different value for count but its not working for cos. If anybody knows why its printing wrong answer... please reply


Solution

  • Your code is right, your test is wrong:

    Instead of cos(deg), it should be cos(radian).

    Moreover, instead of defining PI, you could use the one given in math.h: M_PI:

    #define _USE_MATH_DEFINES
    #include <math.h>
    
    // from here, you can use M_PI 
    
    

    You can also improve your code

    1. Since cosine function is periodic and the Taylor series is better near 0, you should clamp the input number in [-180, 180] range

    2. Factorial function could be computed faster: you have to compute 2!, 4!, 6!... if you store 4! for instance, 6! can be computed with only 2 multiplications instead or recomputing from the start (like you do for sign instead of calling pow(-1, n)

    3. Same for the x^(2n)