I want to print the value of sin(x) using its Taylor series.
I must add terms until the absolute value of a term becomes < 10e-06
#include <stdio.h>
#include <math.h>
double val(double, double);
int main(void){
double x,eps=10e-06;
printf("\nEnter value of x: ");
scanf("%lf",&x);
printf("\nCalculated value: %lf\n",val(x, eps));
return 0;
}
double val(double x, double eps){
int i;
double t=x, sum=0;
if(fabs(x)<= eps) return 0;
for(i=1;i<=20; i++){
sum+=t;
t*=-(x*x)/((2*i+1)*(2*i));
if(fabs(t)>=eps) break;
}
return sum;
}
But I am getting the same output as my input(that is I am getting x in output).
Can someone tell me what is wrong.
The problem is here:
if(fabs(t)>=eps) break;
You're breaking out of the loop if the term is greater than the epsilon value. You want to check if it's less:
if(fabs(t)<eps) break;