问题
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?
回答1:
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...)
回答2:
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
h(k,n)=(k==n)?1.0/n:(1.0+h(k+1,n)/k)
f(n)=1+h(2,n)
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.
来源:https://stackoverflow.com/questions/21875714/implements-neper-number-e-with-a-recursion-function