c program to implement numerical integration using simpson 1/3 rule
CODE :
#include <stdio.h>
#include <math.h>
double f(double x) {
return x * x;
}
double simpson(double a, double b, int n) {
double h = (b - a) / n;
double sum = f(a) + f(b);
for (int i = 1; i < n; i++) {
if (i % 2 == 0) {
sum += 2 * f(a + i * h);
} else {
sum += 4 * f(a + i * h);
}
}
return (h / 3) * sum;
}
int main() {
double a = 0;
double b = 1;
int n = 100;
double integral = simpson(a, b, n);
printf("The integral of f(x) = x^2 from %f to %f is %f\n", a, b, integral);
return 0;
}
output :
The integral of f(x) = x^2 from 0 to 1 is 0.333333
.png)
Comments
Post a Comment