Print the Approximate Integral
In this step, we will enhance our integral approximation program by adding more detailed output and comparing the numerical result with the exact integral value.
Open the previous source file and update the code:
cd ~/project
nano integral_approximation.c
Modify the code to include more comprehensive output:
#include <stdio.h>
#include <math.h>
// Define the function to integrate f(x)
double f(double x) {
return x * x;
}
// Exact integral calculation for x^2 from 0 to 1
double exactIntegral() {
return 1.0 / 3.0;
}
// Trapezoidal Rule Implementation
double trapezoidalRule(double a, double b, int n) {
double h = (b - a) / n; // Width of each trapezoid
double sum = 0.5 * (f(a) + f(b)); // First and last points
for (int i = 1; i < n; i++) {
double x = a + i * h;
sum += f(x);
}
return sum * h;
}
int main() {
// Define the interval [a, b]
double a = 0.0; // Lower bound
double b = 1.0; // Upper bound
int n = 100; // Number of trapezoids
double approximateIntegral = trapezoidalRule(a, b, n);
double exact = exactIntegral();
double error = fabs(approximateIntegral - exact);
double percentError = (error / exact) * 100.0;
// Formatted output with detailed information
printf("Integral Approximation Results\n");
printf("------------------------------\n");
printf("Function: f(x) = x^2\n");
printf("Interval: [%.2f, %.2f]\n", a, b);
printf("Number of Trapezoids: %d\n", n);
printf("\nNumerical Results:\n");
printf("Approximate Integral: %.6f\n", approximateIntegral);
printf("Exact Integral: %.6f\n", exact);
printf("\nError Analysis:\n");
printf("Absolute Error: %.6f\n", error);
printf("Percent Error: %.4f%%\n", percentError);
return 0;
}
Compile and run the updated code:
gcc -o integral_approximation integral_approximation.c -lm
./integral_approximation
Example output:
Integral Approximation Results
------------------------------
Function: f(x) = x^2
Interval: [0.00, 1.00]
Number of Trapezoids: 100
Numerical Results:
Approximate Integral: 0.333333
Exact Integral: 0.333333
Error Analysis:
Absolute Error: 0.000000
Percent Error: 0.0000%
Key improvements in this version:
- Added
exactIntegral()
function to compare numerical result
- Calculated absolute and percentage errors
- Provided more detailed and formatted output