Michael Ali Michael Ali - 11 months ago 107
C++ Question

C++ Program to Calculate e constant using loops

I was asked to create a simplistic program to calculate e by asking for a value i (degree of accuracy) and then using the formula 1 +1/1! + 1/2! + 1/3! + ⋯ + 1!
I am getting a very close value but it is still not correct. Where did I go wrong, and what are ways to improve the code?

#include <iostream>
using namespace std;

int main()
double e=0.0;
double factorial=0;
int i=0;
int j,k=0;//counter variables

cout<<"Enter degree of accuracy: ";

for(j=0;j<=i;j++) //for loop to calculate 'e'
factorial=1; //To reset factorial to 1 for every value of j
for(k=1;k<=j;k++)//for loop to calculate factorial
cout<<"Value for e given i: "<<e<<endl;

return 0;

Answer Source

Two areas for improvement:

  1. Your "not correct" is probably caused by round-off error. When summing a descending sequence of positive numbers, you'll always have less round-off error by summing from smallest to largest. You can do this by computing an array of numbers [1/1!, 1/2!, 1/3!, ..., 1/i!] and summing from the end. At the same time, you might want to look at algorithms for compensating for round-off error. A good reference is the Wikipedia article on the Kahan summation algorithm.

  2. You are doing a lot more work computing the factorial than you need to do. Each time through the outer loop, you need to compute the factorial of i, but (other than the first time) you've just finished computing the factorial of the previous value (i-1). So rather than resetting factorial to 1 and running through the inner loop, just multiply the previous factorial value by i and your done. (Oh, and initialize factorial to 1 instead of 0 at the start of the program.)

Also, I'm not sure if "degree of accuracy" is the same as "number of terms in the expansion". You might want to clarify that with whoever asked you to create this program.