Thursday 14 June 2012

Using Taylor's series implement sin(x), cos(x), e^x

/*
#include<stdio.h>
#include<math.h>
double fact(int num)
{
if(num==0)
return 1;
else
return (fact(num-1))*num;
}
main()
{
int ch,i,neg,c;
float val=1,x=0;
double t=0.0,sin=0.0,cos=1.0;
a: printf("Enter the value of x : ");
scanf("%d",&x);
t=(x*3.14)/180;
printf("\n\t----------Select your Choice------------\n");
printf("\n\t1. e^x");
printf("\n\t2. sin x");
printf("\n\t3. cos x");
printf("\n\t4. Exit");
printf("\n\n-----------------------------------------------------\n\n")
printf("\n\nEnter your Choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
for(i=1;i<100;i++)
val+=pow(x,i)/fact(i);
printf("\ne^%f = %.3f\n",x,val);
break;
case 2:
neg=-1;
for(i=1;i<=20;i++)
{
neg=neg*-1;
sin=sin+((pow(t,i)/fact(i))*neg);
}
printf("\nsin(%f) = %.3f\n",x,sin);
break;
case 3:
neg=1;
for(i=2;i<=20;i+=2)
{
neg=neg*-1;
cos=cos+((pow(t,i)/fact(i))*neg);
}
printf("\ncos(%f) = %.3f\n",x,cos);
break;
case 4:
printf("\nEXITED\n");
exit(0);
default:printf("\nINVALID CHOICE\n");
break;

}
printf("\nDO YOU WANT TO CONTINUE(Y/N) : \n");
printf("\npress 1 to continue......... : ");
scanf("%d",&c);
if(c==1)
goto a;
}
/*
---------------OUTPUT---------------

Enter the value of x : 0

----------Select your Choice------------

1. e^x
2. sin x
3. cos x
4. Exit

-----------------------------------------------------

Enter your Choice : 1

e^0.000000 = 1.000

DO YOU WANT TO CONTINUE(Y/N) :

press 1 to continue......... : 1
Enter the value of x : 0

----------Select your Choice------------

1. e^x
2. sin x
3. cos x
4. Exit

-----------------------------------------------------

Enter your Choice : 2

sin(0.000000) = 0.000

DO YOU WANT TO CONTINUE(Y/N) :

press 1 to continue......... : 1
Enter the value of x : 0

----------Select your Choice------------

1. e^x
2. sin x
3. cos x
4. Exit

-----------------------------------------------------

Enter your Choice : 3

cos(0.000000) = 1.000

DO YOU WANT TO CONTINUE(Y/N) :

press 1 to continue......... : 1
Enter the value of x : 0

----------Select your Choice------------

1. e^x
2. sin x
3. cos x
4. Exit

-----------------------------------------------------

Enter your Choice : 6

INVALID CHOICE

DO YOU WANT TO CONTINUE(Y/N) :

press 1 to continue......... : 1
Enter the value of x : 0
----------Select your Choice------------
1. e^x
2. sin x
3. cos x
4. Exit
-----------------------------------------------------
Enter your Choice : 4
EXITED

1 comment:

  1. I have no idea where is the problem but for me it is not working properly.. it alwazs show result just 0

    ReplyDelete