Thursday, September 13, 2012

Sin Cos Function Implementation in C program

Sin Cos Functions Implementation in C program

Question :Write functions to calculate the sine and cosine of their input. Choose appropriate types for both argument and return value. The series (given below) can be used to approximate the answer. The function should return when the value of the final term is less than 0.000001 of the current value of the function.
sin x = x - pow(x,3)/fact(3) + pow(x,5)/fact(5)...
cos x = 1 - pow(x,2)/fact(2) + pow(x,4)/fact(4)...
Note the fact that the sign in front of each term alternates (--+--+--+...). pow(x,n) returns x to the nth power, fact(n) factorial of n (1 × 2 × 3 × ⋯ × n). You will have to write such functions. Check the results against published tables.(http://publications.gbdirect.co.uk/c_book/chapter4/exercises.html)



Solution:

#include<stdio.h>
#include<math.h>
int fact(int);
double sine(double);
double cosine(double);

int main()
{
double x,rad,pi=3.14;
printf("Enter the Value of x:\n");
scanf("%lf",&x);
rad=x*(pi/180);
double sinr,cosr;
sinr=sine(rad);
printf("\n");
cosr=cosine(rad);
printf("\nSin(X):%f and Cos(X):%f\n",sinr,cosr);
return 0;
}

int fact(int a)
{
int i,factr=1;
if(a==0)
 return 1;
for(i=1;i<=a;i++ )
  factr=factr*i;
return factr;
}

double sine(double sx)
{
int pv=1,pn=0;
double sums=0,c=1;
while(c>0.000001)
{
c=(pow(sx,pv)/fact(pv));
printf("\t %f",c);
sums=sums+c*pow(-1,pn);
pv=pv+2;
pn++;
}
return sums;
}

double cosine(double cx)
{
int pv=0,pn=0;
double sumc=0,c=1;
while(c>0.000001)
{

c=(pow(cx,pv)/fact(pv));
printf("\t %f",c);
sumc=sumc+c*pow(-1,pn);
pv=pv+2;
pn++;
}
return sumc;
}


0 comments:

Post a Comment