Print the Approximate Integral
In this final step, we'll enhance our Simpson's Rule implementation by adding more detailed output and comparing the numerical approximation with the exact integral value.
Open the previous file:
cd ~/project
nano simpson_integration.c
Update the code to include more comprehensive output:
#include <stdio.h>
#include <math.h>
// Function to integrate: f(x) = x^2
double f(double x) {
return x * x;
}
// Exact integral calculation for f(x) = x^2 from a to b
double exact_integral(double a, double b) {
return (pow(b, 3) - pow(a, 3)) / 3.0;
}
// Simpson's Rule implementation
double simpsons_rule(double a, double b, int n) {
double h = (b - a) / n; // Width of each subinterval
double sum = f(a) + f(b); // First and last points
// Compute sum of even and odd points
for (int i = 1; i < n; i++) {
double x = a + i * h;
sum += (i % 2 == 0 ? 2 : 4) * f(x);
}
return (h / 3) * sum;
}
int main() {
// Define integration interval [a, b]
double a = 0.0; // Lower bound
double b = 1.0; // Upper bound
int n = 100; // Number of subintervals (must be even)
// Compute approximation and exact integral
double approx_integral = simpsons_rule(a, b, n);
double exact_value = exact_integral(a, b);
double error = fabs(exact_value - approx_integral);
// Print detailed results
printf("Integral Approximation Results:\n");
printf("------------------------------\n");
printf("Function: f(x) = x^2\n");
printf("Interval: [%.2f, %.2f]\n", a, b);
printf("Number of Subintervals: %d\n\n", n);
printf("Approximation (Simpson's Rule): %.6f\n", approx_integral);
printf("Exact Value: %.6f\n", exact_value);
printf("Absolute Error: %.6f\n", error);
printf("Relative Error: %.4f%%\n", (error / exact_value) * 100);
return 0;
}
Compile and run the code:
gcc simpson_integration.c -o simpson_integration -lm
./simpson_integration
Example output:
Integral Approximation Results:
------------------------------
Function: f(x) = x^2
Interval: [0.00, 1.00]
Number of Subintervals: 100
Approximation (Simpson's Rule): 0.333333
Exact Value: 0.333333
Absolute Error: 0.000000
Relative Error: 0.0000%
Key additions in this step:
- Added
exact_integral()
function to calculate the true integral value
- Computed absolute and relative error
- Created a formatted output showing detailed integration results