Reputation: 1
I know there are many examples of this problem but I tried to write a different one myself. This is using the Taylor series e^x = 1 + x/1! + x^2/2! + x^3/3! + ...... My code compiles and runs but it wont output the correct answer for some imputes and I'm not sure why. is this even usable code or should i scrap it?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double final,power,end_n = 1.0,e=1.0,x=2.0, n;
cout<< "n: ";
// usually enter 5 for test
cin>> n;
while (n>1){
power = pow(x,n);
end_n = end_n*n;
e= (power/end_n)+e;
n--;
}
final =e+x;
cout<< final;
return 0;
}
Upvotes: 0
Views: 7213
Reputation: 26040
You could actually employ a Horner-like scheme that uses the counting down in an essential manner
1 + x/1! + x^2/2! + x^3/3! + … + x^n/n! = (((((x/n+1)*x/(n-1)+1)*x/(n-2)+…)*x/1+1
e = 1.0;
while (n>0){
e = e*x/n + 1;
n--;
}
Compare the approximations of e^x
and 1/(e^-x)
for positive x
for exactness.
Explore (e^(x/4))^4
for better exactness.
Upvotes: 0
Reputation: 72
I think you are close. Maybe you want something more like this:
#include <iostream>
#include <cmath>
using namespace std;
double factorial(long n)
{
double result = n;
while(--n) result*=n;
}
int main()
{
long n, power;
double final, e=1.0, x=2.0;
cout<< "n: ";
// usually enter 5 for test
cin>> n;
while (n>1)
{
power = pow((double)x, (double)n);
end_n = factorial(n);
e = (power/end_n)+e;
n--;
}
final = e+x;
cout<< final;
return 0;
}
Upvotes: 0
Reputation: 240531
To be very clear about something that others are hinting at: if your loop counted up from 1 to n then end_n
would equal n! at each step. But counting down, it doesn't. Look at the examples from 1 to 5:
n | n!
1 | 1
2 | 2
3 | 6
4 | 24
5 | 120
n | end_n
5 | 5
4 | 20
3 | 60
2 | 120
1 | 120
Since absolutely none of your denominators are right, it's a surprise if your code is only wrong for some inputs — in fact it's probably only correct for x=0.
Finally, I hope that this is just an exercise for learning. If you really need the value of e^x you should use exp(x)
.
Upvotes: 1
Reputation: 67447
I honestly have no idea what your reasoning is, at all. The code for that particular expansion is trivially simple:
double x;
cin >> x;
double oldres, res=1, top=1, bottom=1;
int iter=1;
do {
oldres=res; // to calculate the difference between iterations
++iter; // next iteration
top*=x; // multiply by one x for each iteration
bottom*=(iter-1); // multiply by the iteration number for each iteration
res+=top/bottom; // and add the fraction to the result
} while(fabs(res-oldres)>.1); // while the difference is still large
cout << res; // done, show the result
Upvotes: 1