Our professor has taught us to find Taylor’s series by recursion using a static summation variable that accumulates the summation of each term and then multiples with itself with each iteration.
#include <stdio.h>
double t(int n,int m){
static double a = 1.0;
if(m==0)
return a;
a = 1+(double)n/m*a;
return t(n,m-1);
}
int main(){
printf("%lfn",t(4,1500));
}
This, yields the desired accuracy and result.
I tried to implement the code using a single return statement:
#include <stdio.h>
double e(int x, int m){
if(m==0)
return 1.0;
return 1+((double)x/m)*e(x,m-1);
}
int main(){
printf("%lfn",e(4,1500));
}
This, yields an output of 1.002674
.
What is the difference between the two? What causes this code to lead this inaccuracy?
Amitava Bose is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.