Approximate e^x without the math library in C
February 9, 2012
This is a simple C program that approximates e^x based on its Taylor series. It guarantees that the error is smaller than the input value r.
/* Daeyun Shin */
#include <stdio.h>
#include <stdlib.h>
double power(double x, int y){
int i;
double result=1;
for(i=0;i<y;i++) result*=x;
return result;
}
int factorial(int x){
int result=1;
for(;x>1;x--) result*=x;
return result;
}
double nth_taylor(double x,int n,int errorChecking){
if (errorChecking && x<0) x=-x;
return power(x,n-1)/factorial(n-1);
}
int main(){
int n=0;
double ans=0,r,x;
printf("Enter in the value of x:");
scanf("%lf",&x);
printf("Enter in the value of r:");
scanf("%lf",&r);
while(nth_taylor(x,n,1)>=r){
n++;
ans+=nth_taylor(x,n,0);
}
printf("Number of terms = %d\nAnswer = %lf",n,ans);
return 0;
}
