Taylor Series
e^x = 1 + x / 1 + x^2 / 2! + x^3 / 3! + x^4 / 4! + ... n times
This is mostly a combination of recursive operations we have already seen:
sum(n) = 1 + 2 + 3 + ... + n sum(n - 1) + n
fact(n) = 1 * 2 * 3 * ... * n fact(n - 1) * n
pow(x, n) = x * x * x * ... n times pow(x, n - 1) * x
This function must perform three operations, but can only return one result. We can use static variables to write the function.
double e(int x, int n) {
static double p = 1, f = 1;
double r;
if (n == 0)
return 1;
else {
r = e(x, n - 1);
p = p * x;
f = f * n;
return r + p / f;
}
}
// e(1, 10) = 2.718282