Reputation: 1975
How would I write a recursive static method that uses an (n+1) term MacLaurin series to compute e^x, called e(x,n), by using the following recursive formulation:
e(x,0)= 1
e(x,n)= e(x,n-1) + x^n/n!, if n>0
Also, my method signature needs to use the following:
public static double eTwo(double x, long n)
Been stuck for a while, any thoughts guys?
Upvotes: 1
Views: 2366
Reputation: 12129
A version which is likely a little more efficient would be to use a loop instead of recursion, because only a single stack frame needs to be allocated:
static double eTwo(double x, long n) {
double result = 1;
for (long i = 1; i < n; i++)
result += Math.pow(x, (double) i) / (double) factorial(i);
return result;
}
static long factorial(long n) {
long result = 1;
for (long i = 1; i <= n; i++)
result *= i;
return result;
}
Upvotes: 0
Reputation: 698
This is simplest solution that get on my mind, did you try it?
public static double eTwo(double x, long n){
if(n==0)
return 1;
else
return eTwo(x,n-1) + Math.pow(x, n)/factorial(n);
}
public double factorial (n){
if(n==0)
return 1;
else
return n*factorial(n-1);
}
Upvotes: 2