//this simply calucaltes the exponent with a Taylor's expansion // to demonstrate the negative aspect of alternating series #include #include #include main() { int i; double x; double xprod,factorial,sexp; double actualvalue; int flag; char filename[25]; FILE *outfile; printf("Enter x value\n"); scanf("%lg",&x); printf("Name of output file\n"); scanf("%s",filename); outfile=fopen(filename,"w"); fprintf(outfile,"N\tPsum\tFacErr\n"); //xprod is used to keep track of the power of x^i //sexp is the Taylor's estimates of exp(x) //factorial is the i! - i should not be much larger than 50 in this case factorial=1.0; xprod=1.0; sexp=1.0; actualvalue=exp(x); //this part deal with problem with negative x if(x<0) { flag=1; x=-x; } else flag=0; for(i=1;i<=30;i++) { //increment variables factorial*=i; xprod*=x; sexp+=xprod/factorial; //if x<0, Taylor's series can be use effectively with 1/sexp. if(flag) fprintf(outfile,"%d\t%lg\t%lg\n",i,1.0/sexp,log10(fabs(1.0/sexp-actualvalue)/actualvalue)); else fprintf(outfile,"%d\t%lg\t%lg\n",i,sexp,log10(fabs(sexp-actualvalue)/actualvalue)); } return 0; }