I have been trying to approximate e using series representation to get as many precision digits as possible using the code below, but no matter how many terms I compute, the number of precision digits seems to remain the same. ie:
2.71828198432922363281250000000000000000000000000000
Is it my approach that’s wrong?
Here is the code:
1 #include <stdio.h>
2 #include <iostream>
3 #include <math.h>
4 using namespace std;
5
6 float factorial (float a)
7 {
8 if (a > 1)
9 {
10 return (a * factorial (a-1));
11 } else
12 {
13 return 1;
14 }
15 }
16
17 int main()
18 {
19 float sum = 0;
20 int range=100000;
21
22 for (int i=0; i<=range;i++)
23 {
24 sum += pow(-1,i)/factorial(i);
25 }
26 sum = pow(sum,-1);
27 printf("%4.50f\n", sum);
28 }
To get more exact digits, you should write your on data class which store more digit, say, 1000 digits. The hardest part is to wirte the +, -, *, / operations.
If what you want is just to experiment with the math formula, you can choose another language, such as Python. It has data types like
Decimal, Fractionthat can do more precise calculating.I love math so I do write a python script to test the formula:
Here’s the result: