In: Computer Science
Write C code to approximate Sin(x) and Cos(x) function using Taylor’s series. The angle x is expressed in radians. Use the first FIVE terms of Taylor’s series to approximate Sine/Cosine function.
a. Compare your Taylor’s series approximation of Sine/Cosine function with the math.h implementation of sin and cos function.
b. Determine tan(x) from Taylor’s series approximation of Sine/Cosine functions, for x = 0, PI/4, PI/2, PI. Use PI = 3.14159.
#include<stdio.h>
#include<math.h>
double fact(int n)
{
if(n==0)
return 1;
else
return (fact(n-1))*n;
}
int main()
{
int f,i,s,c;
float val=1,x=0;
double t=0.0,sin=0.0,cos=1.0;
float pi=3.14159;
float l=0,m=(pi*pi)/720,n=(pi*pi)/360;
printf("\n\tEnter the function\n");
printf("1. sin \n");
printf("2. cos \n");
printf("3. tan \n");
scanf("%d",&f);
int angle;
switch(f)
{
case 1:
s=-1;
printf("Enter the value of x :
");
scanf("%f",&x);
t=(x*3.14)/180;
for(i=1;i<=5;i++)
{
s=s*-1;
sin=sin+((pow(t,i)/fact(i))*s);
}
printf("\nsin(%f) =
%.3f\n",x,sin);
break;
case 2:
printf("Enter the value of x :
");
scanf("%f",&x);
t=(x*3.14)/180;
s=1;
for(i=2;i<=5;i+=2)
{
s=s*-1;
cos=cos+((pow(t,i)/fact(i))*s);
}
printf("\ncos(%f) =
%.3f\n",x,cos);
break;
case 3:
printf("\nEnter any of these
angles: 1- 0, 2- pi/4, 3- pi/2\n");
scanf("%d",&angle);
if(angle==1){
s=-1;
for(i=1;i<=5;i++)
{
s=s*-1;
sin=sin+((pow(l,i)/fact(i))*s);
}
int s1=1;
for(i=2;i<=5;i+=2)
{
s1=s1*-1;
cos=cos+((pow(l,i)/fact(i))*s1);
}
float tan=sin/cos;
printf("\ntan(%f) =
%.3f\n",l,tan);
}
else if(angle==2){
s=-1;
for(i=1;i<=5;i++)
{
s=s*-1;
sin=sin+((pow(m,i)/fact(i))*s);
}
int s1=1;
for(i=2;i<=5;i+=2)
{
s1=s1*-1;
cos=cos+((pow(m,i)/fact(i))*s1);
}
float tan=sin/cos;
printf("\ntan(%f) =
%.3f\n",m,tan);
}
else if(angle==3){
s=-1;
for(i=1;i<=5;i++)
{
s=s*-1;
sin=sin+((pow(n,i)/fact(i))*s);
}
int s1=1;
for(i=2;i<=5;i+=2)
{
s1=s1*-1;
cos=cos+((pow(n,i)/fact(i))*s1);
}
float tan=sin/cos;
printf("\ntan(%f) =
%.3f\n",m,tan);
}
break;
default:printf("\n Invalid
entry.\n");
}
}