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?
Still not sure what you want res for. In fact, if I got creative with the sign of n this doesn't need i either.
double f(int i, int n)
{
return (i == 0) ? ((n <= 1) ? 1 : n * f(0,n-1))
: ((n < 1) ? 1 : 1/f(0, n) + f(i,n-1));
}
int main()
{
for (int n=1; n<16; ++n)
std::cout << std::setprecision(16) << f(1,n) << std::endl;
return 0;
}
Output
2
2.5
2.666666666666667
2.708333333333333
2.716666666666666
2.718055555555555
2.718253968253968
2.71827876984127
2.718281525573192
2.718281801146385
2.718281826198493
2.718281828286169
2.718281828446759
2.71828182845823
2.718281828458995
This was what I meant about toying with the sign for n to eliminate i as well:
double f(int n)
{
return (n < 0) ? ((n == -1) ? 1 : -n * f(n+1))
: ((n < 1) ? 1 : 1/f(-n) + f(n-1));
}
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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With