EEE 306 Lab 5 : Taylor series sine and cosine

August 9, 2017
By shp

Task #1

Write a program to find an estimate of any value of cos(x). You should take input the value of x in degree, the maximum number of iteration, and the minimum error requirement

Sample code

#include<stdio.h>
#include<math.h>
int fact(int n)
{
 if (n==1){return 1;}
 return n*fact(n-1);
}
int main()
{
 int i,j, iter, sign=1;
 double x, es,ea, previous=1, approx=1, curr_approx;
 scanf("%lf", &x);
 x=(x/180)*3.141592654;
 //printf("%lf\n", x);
 scanf("%d", &iter);
 scanf("%lf", &es);
 for (i=1;i<iter;i++)
 {
 j=i*2;
 curr_approx=(pow(x,j)/(fact(j)));
 if (sign%2==1)
 {
 approx=approx-curr_approx;
 }
 else {approx=approx+curr_approx;}

ea=fabs(((approx-previous)/approx)*100);
 previous=approx;
 sign++;
 printf("\n %lf\t %lf", approx, ea);
 if (ea<es) break;

}

printf("\n%lf", approx);
}

Task #2

Write a program to find an estimate of any value of sin(x). You should take input the value of x in degree, the maximum number of iteration, and the minimum error requirement

Sample code

#include<stdio.h>
#include<math.h>
int fact(int n)
{
 if (n==1){return 1;}
 return n*fact(n-1);
}
int main()
{
 int i,j, iter, sign=0;
 double x, es,ea, previous=0, approx=0, curr_approx;
 scanf("%lf", &x);
 x=(x/180)*3.141592654;
 //printf("%lf\n", x);
 scanf("%d", &iter);
 scanf("%lf", &es);
 for (i=1;i<iter;i++)
 {
 j=(i*2)-1;
 curr_approx=(pow(x,j)/(fact(j)));
 if (sign%2==1)
 {
 approx=approx-curr_approx;
 }
 else {approx=approx+curr_approx;}

ea=fabs(((approx-previous)/approx)*100);
 previous=approx;
 sign++;
 printf("\n %lf\t %lf", approx, ea);
 if (ea<es) break;

}

printf("\n%lf", approx);
}

Assignment

There is no assignment for this lab.

Leave a Reply