Taylor series expansion of cos(x) is not working

121 Views Asked by At
#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

2

There are 2 best solutions below

2
Mathieu On BEST ANSWER

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)

0
duffymo On

Your code is inefficient. You call factorial over and over without memoizing it.

Here are better examples in Python. No calls to a factorial function needed. You should be able to port them.

def cosine(t, n):
    result = 0.0
    term = 1.0
    sign = 1.0
    for i in range(0, n):
        result += sign*term
        sign *= -1.0
        term *= t*t/(2*i+1)/(2*i+2)
    return result

def sine(t, n):
    result = 0.0
    term = t
    sign = 1.0
    for i in range(1, n):
        result += sign*term
        sign *= -1.0
        term *= t*t/(2*i)/(2*i+1)
    return result