Recursive Calculation of the Exponential Function in C
e(x)=1+ x/1! + x^2/2! + x^3/3! + ... + x^n/n! with x^n/n! < Ɛ #include< stdio.h> #include< stdlib.h> unsigned long fact_recursive (unsigned short nombre) { if (number == 0) return 1; else return number * fact_recursive(number - 1); } unsigned int puiss(long int x, int n) { if(n == 0) return 1; if(n == 1) return x; int x2 = powers(x,n/2); if(n%2 == 0) return x2*x2; return x2 * x2 * x; } double calcul_formule(int x, int n, int epsilon) { double fraction = (double)puiss(x,n) / (double)fact_recursive(n); if(n==0) { return 1; } else{ //Verification of the condition if powers(x,n)/n! > epsilon if(fraction < epsilon) return fraction+calcul_formule(x,n-1,epsilon); else return calcul_formule(x,n-1,epsilon); }
} int main(int argc, char *argv[]) { int x,n,epsilon; printf("Enter the value of x: "); scanf("%d",& x); printf("Enter the value of n: "); scanf("%d",& n); printf( Enter the value of Epsilon: "); scanf("%d",& epsilon); //calculation of the formula printf("exp( %d ) = %f\n",x,calcul_formule(x,n,epsilon) ); system("pause"); }
Advertisement
AdBlock Detected
Please disable your ad blocker and refresh the window to use this website.