Implements non-fathom number (e) with recursion function

I want to calculate Neper number (e) with a recursion function. I have a formula for calculating:

e = (1/0!) + (1/1!) + (1/2!) + (1/3!) +.,.

I have some code, but it will not 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 2.5, but it should be 2. Where is the problem?

+3
source share
2 answers

Not sure what you want resfor. In fact, if I received a creative with a sign n, this is not necessary i.

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 had in mind to indicate the sign nfor excluding i:

double f(int n)
{
    return (n < 0) ? ((n == -1) ? 1 : -n * f(n+1))
        : ((n < 1) ? 1 : 1/f(-n) + f(n-1));
}

. . , 1/n!, + ( 1/(n-1)!, ..)

+4

, , .

1/0! +1/1! +1/2! +... + 1/n! , 2 + 1/2 * (1 + 1/3 * (1 +... 1/n))),

h(k,n)=(k==n)?1.0/n:(1.0+h(k+1,n)/k)
f(n)=1+h(2,n)

, , , e = exp (1/8) ^ 8, .

+1

All Articles