e^x=1 + x^n/1!....question - please explain so I can understand.

OK, I've spent hours looking at the posts on this equation and I still cannot figure out how to properly write the code to compute e^x after prompting user for the exponent and the desired accuracy. Could someone please help? Here is what I've tried so far...I know it is completely wrong but I don't know what else to try.

while (i <= accuracy)
{
factorial *= i;
e += 1/factorial;
i++;
while(x<=num)
{

term = term * x / factorial;
x++;
x = x+1;
total = total + term;
}
}
What data types are those variables? It looks like you're falling prey to integer division.
I'm not sure why there are nested while loops. A single loop should be sufficient.
LB, I'm using double for the variables. Chervil, I guess that is part of my question, how would I or could I do it without nesting the loops? I came up with the following but it doesn't work either. Not sure quite how to get e^x. Any thoughts or suggestions?

for (x=1; x<= exponentX; x++)
{
factorial *= x;
ex = ex+ (pow(x, exponentX)/factorial);
}
Well, I've posted on this topic before, sometimes it's hard for me to explain without actually showing the completed code. Here's the series again:

ex = 1 + x/1! + x2/2! + x3/3! + x4/4! + ...

Now that is very repetitive, and there's a simple pattern here, where each term of the series can be derived from the previous by one multiply, and one divide.

first term  = 1
second term = (first term)  * x / 1
third term  = (second term) * x / 2
fourth term = (third term)  * x / 3
fifth term  = (fourth term) * x / 4
...


One comment I would make. I think it's not really appropriate to use the pow() function here, as that is effectively using the built-in version of ex in its internal workings.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>     // std::cout
#include <iomanip>      // std::setprecision
#include <math.h>       // log10
using namespace std;

int main()
{
  double x;
  cout << "       x:"; cin >> x;

  double accuracy;
  cout << "accuracy:"; cin >> accuracy;

  double term = 1; // n = 0;
  double result = term; // 1 + ...

  for (unsigned n = 1; 2*term > accuracy; ++n) {
    term = term * x / n; // the n-th term
    result += term; // ... + x^n/n!
  }

  cout << "  exp(x):"
       << std::setprecision(accuracy < 1 ? -log10(accuracy) + 2 : 3)
       << result << endl;

  return 0;
}


       x:1
accuracy:0.0001
  exp(x):2.7183
Topic archived. No new replies allowed.