javarecursiontaylor-series

Computing e^x using recursion and taylor series


So I am required to recursively calculate e^x using a factored form of a Taylor series:

equation: e^x = 1 +x + (x^2)/2! + ... + ((x^n)/n!))

factored form: e^x = 1 + x (1+x/2*(1+x/3*(...(1+x/n))))

In the function definition below, 'x' is the power and 'n' is the total number of terms to estimate e^x. I would prefer if someone could point me in the right direction. I have tried many different ways, including using a base case of the innermost term of the factored equation, but to no avail.

static double eThree(double x, long n) {
   //this is what i tried
   if(n==0){
        return 1 +x/n;
    }else{
        double a= (1+(x/n)) * (eThree(x,n-1));
        System.out.println(a);
        return a;
    }


}

I have realized that 'n' should increase not decrease as I have attempted, however, the original call to the function has the total number of iterations in variable 'n' and there is no way to keep track of the total number of iterations throughout all the recursive calls.

the value of each term's divisor in (1 +(x/n)), where n is the divisor, should increase by one each time, and in the final iteration be equal to the total number of iterations.


Solution

  • Since the method is static, you can actually just store it in a static variable in the first call. You'll need to throw an if statement in to check if it's the first iteration too. I'll add code later but don't have time right now.

    Or you can keep track of the number of iterations in a variable. Delegate to another method which is the "real" recursive method, and pass different arguments.

    All kinds of different possible solutions.

    You could turn it in to a loop, but that would possibly not impress your supervisor.