I've written a small code to calculate the constant e with 40 digits precision, but, apparently due to the limitations of long double, it's not accurate. Here's the code:
For some reason, the results of 1/21! to 1/40! are calculated but are not added to the rest of the series, resulting in a not-so-precise output. I can't figure out why this happens.Code:#include <stdio.h>
long double fact(long double n)
{
long double sum;
sum = n;
if(n == 0)
return 1;
else
{
while(n != 1)
{
sum = sum * (n - 1);
n = n - 1;
}
return sum;
}
}
main()
{
int counter;
long double e, k;
k = e = 0;
for(counter = 0; counter < 40; counter++)
{
e = e + (1.0/fact(k));
++k;
}
printf("%.40f\n", e);
}
Could anyone suggest anything, perhaps another algorithm, for this calculations which does not rely on any special library?