I am trying to compute e^x and have made a factorial function that I verified is correct. The factorial function is not shown. I suspect the error is in the for statement with the **.
The main is just a check, the main outputs "E_to_X(0) is inf should be 1" and "E_to_X(1) is inf should be 2.718"
Much thanks for any help.
double E_to_X(double X) {
double x = X;
double sum = 1 + X;
** for (int i = 0; i <= 20; ++i){
** sum += ((pow(x, i)) / (factorial(i)));
}
return sum;
}
// You can change main() in anyway you want
int main() {
cout << fixed << "E_to_X(0) is " << E_to_X(0) << " should be 1" << endl;
cout << fixed << "E_to_X(1) is " << E_to_X(1) << " should be 2.718" << endl;
My bad about the factorial code, should've posted.
Here is the full code.
I tried changing the factorial interval lower to 5 that it was definitely still in the range of int and still got a inf output.
// Test and develop a version of the exp() function - main() has test
// code to check and see if this version of exp() function works properly.
The way you've written factorial, you'll get a return value of 0 for an input of 0, but the factorial of 0 should be 1.
With a return of 0 you end up dividing by 0 in the exponential code, giving inf.
Also, you should just start sum at 0.
And you don't need the extra x variable. Just use the input parameter.
It's a very inefficient implementation since you could easily keep a running factorial going in the exponential function instead of calculating it each time from scratch in a separate factorial function. You could do the same thing for the power.
I know that these functions are not optimal, but this is just a learning exercise for me. So just understanding it was the main focus. And I understand it much better now, so thank you again.
If you want exp(x) - or most other power series for that matter - then the last thing you should do is have a factorial function. As @dutch pointed out, you should keep a running product for each term as each one is a very simple multiple of the previous.
Here,
(rth term) = (previous term) * x / r
Absolutely no need for either a factorial or a power of x.