Im supposed to write an e^x approximation using a taylor series (link to taylor series pdf http://people.math.sc.edu/girardi/m142/handouts/10sTaylorPolySeries.pdf) and im having some trouble. I was given a pi approximation program to help but I don't really understand the code. Please explain to me the pi code and tell me if im anywhere on track for the e^x code. I don't think I am but I just need someone to look at it.
Pi Approximation code
#include <iostream>
#include <math.h>
#include <cmath>
usingnamespace std;
int main() {
double n = 1;
int i = 1;
bool add = false;
double sum = 0;
double oldsum = 0;
do {
oldsum = sum;
if(i%2 != 0) sum += (1/n);
if(i%2 == 0) sum -= (1/n); // set sum as 1
n += 2; // add 2 to n for taylor series
i++; // add one to term number
} while( abs((4.0)*sum - (4.0)*oldsum) > .00000001 );
cout << "Term # " << i << '\t' << "pi approx: " << (4.0)*sum << '\n';
return 0;
}
My code so far
#include <iostream>
#include <math.h>
#inlcude <cmath>
usingnamespace std;
int main() {
double n = 0;
int i = 0; // term number
bool add = false;
double sum = 2;
double oldsum = 0;
double x;
cout << "Input x:";
cin >> x;
1 + x;
do {
double r = (x / !(sum));
sum++;
i++;
}while ( r > .0000001);
cout << "Term number:"<< i <<'\t' << r;
return 0;
}
ok well i just found out I'm calculating e^1 so i dint need an input. So i hour use a for loop instead of a dowhile? Sorry I'm very new to programming. And i would put the fact(i) not! ?
#include <iostream>
#include <math.h>
#include <cmath>
usingnamespace std;
double fact(double c);
//returns factorial of a number
int main() {
int i = 1; // term number
int n = 0; // exponent and divisor number
double sum = 0;
double oldsum = 0;
do {
oldsum = sum;
sum += pow(1, n)/fact(n);
n++;
i++;
} while( sum - oldsum > .0000001);
cout << "Term #:" << i << '\t' << "Approximation:" << sum;
return 0;
}
double fact(double c) {
if( c == 0) return 1;
else {
double m = 1;
while(c > 0) {
m *= c;
c--;
}
return m;
}
}
I see the task is completed, and that is fine. Still, there's one thing I would suggest as a challenge. Try doing the calculation of e without making use of either the pow() or fact() functions. It can be done with very small amount of calculations, since each factorial is derived from the previous with a single multiplication. The same applies to the power, each can be derived from the previous with just a single multiply.
Don't worry about this though, it's only an idea for those who are interested in trying it.
Thank you i wanna try that cause i really am interested in programming and wanna get better cause im not very good now. But i did think about this before i used those functions.