I want to calculate Neper number(e) with a recursion function. I have the formula to calculate it:
e = (1/0!) + (1/1!) + (1/2!) + (1/3!) +. . .
I have the code but it won't work properly:
#include <iostream>
using namespace std;
double f(double res,int i, int n){
return (i == n) ? res: res = res + (1 /f(res,i+1,n)*i);
}
int main(){
cout << f(1,1,2) << endl;
}
The result of this code is 2.5
but it should be 2
. Where is the problem?
I think you are referring to Napier, the inventor of the logarithm.
To compute 1/0!+1/1!+1/2!+...+1/n! recursively and efficiently, you can refactor it as 2+1/2*(1+1/3*(1+...1/n))) to obtain the recursive definition
You will get faster convergence by using the properties of the exponential function, for instance that e=exp(1/8)^8, also known as the strategy of halving-and-squaring.
Still not sure what you want
res
for. In fact, if I got creative with the sign ofn
this doesn't needi
either.Output
This was what I meant about toying with the sign for
n
to eliminate i as well:The results are the same. In both cases the function is defined to dual-purpose it recursive algorithm. When asked to, it computes 1/n!, otherwise it computes the running sum + the next number down (which is 1/(n-1)!, etc...)