I have written the following code to find the Taylor series summation using recursion. Although I am getting correct results but my problem is with the static variable s (declared in code and assigned value 1) whatever may be the value of s I choose output comes out to be same in Code-Blocks IDE which I am using .
#include<iostream>
using namespace std;
double e(int x, int n)
{
static double s=1;
if(n==0)
return s;
s=1+x*s/n;
return e(x,n-1);
}
int main(){
cout<<e(5,100);
}
Can you explain how is this happening?
This is more of a math "problem" than a C one and it's due to the numerical stability of the sequence
sn = 1 + x * sn + 1 / n
used in the body of your function.
Consider the following table, where some of the n
values of s
are showed, for different starting points (0.1, 1, 10, 100) and x = 5
:
======================================================= s n 0.100000 1.000000 10.000000 100.000000 ------------------------------------------------------- 100 1.005000 1.050000 1.500000 6.000000 99 1.050758 1.053030 1.075758 1.303030 98 1.053610 1.053726 1.054886 1.066481 97 1.054310 1.054316 1.054376 1.054973 96 1.054912 1.054912 1.054915 1.054947 95 1.055522 1.055522 1.055522 1.055524 94 1.056145 1.056145 1.056145 1.056145 93 1.056782 1.056782 1.056782 1.056782 ... ... ... ... ... 10 1.877638 1.877638 1.877638 1.877638 9 2.043132 2.043132 2.043132 2.043132 8 2.276958 2.276958 2.276958 2.276958 7 2.626398 2.626398 2.626398 2.626398 6 3.188665 3.188665 3.188665 3.188665 5 4.188665 4.188665 4.188665 4.188665 4 6.235832 6.235832 6.235832 6.235832 3 11.393053 11.393053 11.393053 11.393053 2 29.482632 29.482632 29.482632 29.482632 1 148.413159 148.413159 148.413159 148.413159 -------------------------------------------------------