You are using a version without Ads of this website. Please, consider donating:

### 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.
 ``123456789101112131415161718192021222324252627`` ``````#include // std::cout #include // std::setprecision #include // 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.