Print the Approximation
In this final step, we will enhance our program to print the approximation of e with different levels of accuracy and provide a more detailed output.
Update the C file once more:
cd ~/project
nano e_approximation.c
Replace the previous content with the following comprehensive code:
#include <stdio.h>
#include <math.h>
double factorial(int n) {
if (n == 0 || n == 1) return 1;
double result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
void print_e_approximations() {
double accuracies[] = {1e-1, 1e-3, 1e-6, 1e-9};
int num_accuracies = sizeof(accuracies) / sizeof(accuracies[0]);
printf("e Approximation with Different Accuracy Levels:\n");
printf("---------------------------------------------\n");
for (int i = 0; i < num_accuracies; i++) {
double e = 0;
double term = 1;
int n = 0;
int terms_used = 0;
while (fabs(term) > accuracies[i]) {
e += term;
n++;
term = 1.0 / factorial(n);
terms_used++;
}
printf("Accuracy: %e\n", accuracies[i]);
printf("Approximation: %.10f\n", e);
printf("Terms Used: %d\n", terms_used);
printf("Difference from math.h e: %.10f\n\n", fabs(e - M_E));
}
}
int main() {
print_e_approximations();
return 0;
}
Compile and run the program:
gcc e_approximation.c -o e_approximation -lm
./e_approximation
Example output:
e Approximation with Different Accuracy Levels:
---------------------------------------------
Accuracy: 1.000000e-01
Approximation: 2.7000000000
Terms Used: 4
Difference from math.h e: 0.0182818284
Accuracy: 1.000000e-03
Approximation: 2.7182500000
Terms Used: 8
Difference from math.h e: 0.0000318284
Accuracy: 1.000000e-06
Approximation: 2.7182818000
Terms Used: 14
Difference from math.h e: 0.0000000284
Accuracy: 1.000000e-09
Approximation: 2.7182818285
Terms Used: 21
Difference from math.h e: 0.0000000000
Key improvements in this version:
- Prints approximations at multiple accuracy levels
- Shows number of terms used for each approximation
- Calculates and displays the difference from the standard math library value of e