Approximating the value of e

I am new to C++ and I am trying to write a code that can approximate the value of the Napier constant e from the infinite series e = 1 + 1/1! + ... I read some threads in the forum but none of them seem to address the approach I adopted because instead of a preassigned value of n, the code should allow the user to enter a non-negative integer of their choice and approximate the value of e by summing the reciprocal of the factorials up to the integer.
My code is below, for n = 0, I get the value of e = 1, but for n = 1, I get the value e = 0 and as n increases, the value becomes negative and tends towards -2.71828 from n = 10, which in absolute value, is the right approximation. But I am clueless as to why the negative sign. I spent countless hours on this trying to find the culprit in the code, but failed. Could anyone help me?
Thanks in advance and merry Xmas.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<iostream>
using namespace std;
int main()
{
	//variable declaration and eventual initialization
	
	int factorial, m, k, number;
	double e = 0;
	
	// read the integer
	do{	cout << "Please enter a non-negative integer: ";
		cin  >> number; } while(number < 0);
			
	// computation of the factorials and the approximation of e
	k = number;
//The nested while structure will compute the m! and the expression after will									//compute the sum of 1/m! and e. The outer while makes sure that the values of m
//ranges from o to number. The variable factorial must be initialized to 1 for
// each repetition, otherwise it will hold the product of all m! the result of 
// e would be flawed, this is a logic error.

	while(number-- >= 0){							
	    m = number;
	    factorial = 1;								
	    while(m-- >= 0)								
		  factorial *= (m == 0 ? 1 : m);			
	    e += (1.0 / static_cast<double>(factorial));
	}	
	
	// termination phase and printing of the results
	cout << "The approximation of e with the sums of factorials " << k         
	      << "!" << " is " << e << endl;
	system("PAUSE");
	
	return(0);
	
	}// end function main 
The reason behind this is in your use of the "--" operator. The form your using is called post-decrement operator. So you use the initial value when checking and then decrement afterwards.

so when you write m-- >= 0 and when m is 0 then this is a valid statement resulting in m being decremented to the value -1 and since you have factorial *= (m == 0 ? 1 : m); m is no longer 0 it is -1 therefore factorial gets multiplied by -1.
Last edited on
I am new to C++ as well. I examined your codes and came up with the following:

As guatemala007 suggested, I believe having the post decrement was probably not a good idea.

Several things I want to point out.

First, I changed int type to long long so those variable can store slightly larger integers.

Second, static_cast is not necessary on line 26 since it is dividing 1.0, which is double type, so the integer gets converted to double anyways during mixed operation.

Third, in the while loop in line 21, get rid of the post decrement and change >= to >. Then, you wouldn't need the while loop on line 24. Since 0! = 1, and any number multiplied by 1 is itself.

With those change, I got this and the result is positive, which is what you would expect

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
using namespace std;

int main()
{
    // Changed type from int to long long to accommodate higher number (Factorials tend to get very large)
	long long factorial, m, k, number;          

	double e = 0;

	do{	cout << "Please enter a non-negative integer: ";
		cin  >> number; } while(number < 0);

	k = number;

	while( number >= 0 ){

	    m = number;                 // Create a working copy of number

	    factorial = 1;              // Reset factorial to 1

            // If number is 0, it will skip this while loop and factorial will be 1
	    while ( m > 0 )
            {
                factorial *= m;

                m --;
            }

            // Debugging output to make sure Factorial has been calculated correctly. Comment out when finished
            cerr << "Factorial is " << factorial << endl;       

	    e += (1.0 / factorial);

            number --;
	}

	cout << "The approximation of e with the sums of factorials " << k
	      << "!" << " is " << e << endl;

	return(0);
}



Test Run

1
2
Please enter a non-negative integer: 5
The approximation of e with the sums of factorials 5! is 2.71667
Last edited on
Another view on the same idea. The main loop can be simplified so there is no nested loop.
1
2
3
4
5
6
7
8
    double factorial = 1;
    double e         = 1;   

    for (int i=1; i<=number; i++) 
    {
        factorial *= i;
        e += 1.0 / factorial;
    }
Thanks a lot for your inputs and explanations. They have been very helpful, cheers!
Topic archived. No new replies allowed.