1

I recently picked up the c++ programming language, and I'm trying to calculate the digits of 'e' for a Calculus Project at school. I'll paste the pgoram that I've written below. It's based on e= lim(1+1/x)^x, as x-> infinity. In this program, I set x=100,000. I also set x=1,000,000 and noticed that the answers are somehow being subjected to a round-off error, instead of becoming longer in length.

Program:

#include <iostream>
#include <math.h>
using namespace std;

long double sum;

int main()
 {

    long double x=100000;
    sum= (pow((1+(1/x)),(x)));
    cout<<sum;

 }

Any tips/ advice in making it print out more digits would be great. Thanks in advance.

2 Answers2

2

On the first hand long double is limited in the number of digits it can produce, and because of how the real numbers are implemented it won't produce exact results.

But, to answer your question you can set cout's precision by doing

cout.precision(15);
cout << sum;

Also see this answer for more explanations and details see How do I print a double value with full precision using cout?

Community
  • 1
  • 1
-2

Double in c++ is a floating point number. For accurate calculation like this you need use decimal number.

See this answer about decimal in cpp

Community
  • 1
  • 1
Nikolay Viskov
  • 1,016
  • 6
  • 9