#include #include // Our function to integrate over double ourfunc(double x) { return x*x; } typedef double (*DfD) (double); // Simpson's parabola method double simpsons_int(DfD f, double x0, double x1, int n){ double x, sum, dx = (x1 - x0) / n; sum = f(x1) - f(x0); for(x = x0; x+dx/2 < x1; x += dx) sum += 2.0 * f(x) + 4.0 * f(x + dx/2); return sum * dx / 6.0; } // Midpoint Rectangle Method double midpoint_int (DfD f, double x0, double x1, int n){ int i; double x, dx, sum = 0.0; dx = (x1-x0)/ n; for (i = 0, x = x0 + dx/2; i < n; i++, x += dx) sum += f(x); return sum * dx; } // Trapezoidal Line method double trapezoidal_int (DfD f, double x0, double x1, int n){ double x, dx, sum; int i; dx = (x1-x0)/ n; sum = (f(x0) + f(x1))/2; for (i=1, x = x0 + dx; i < n; i++, x += dx) sum += f(x); return sum * dx; } int main() { int sx = 0; // start point int fx = 2; // end point of interval int n = 2; // number of segments printf("Start Point: %d\n", sx); printf("End Point: %d\n", fx); printf("Segments: %d\n", n); printf("Seg. Width: %g\n\n", (((double)fx-sx)/n)); printf("Midpoint: %f\n", midpoint_int(ourfunc, sx, fx, n)); printf("Simpsons: %f\n", simpsons_int(ourfunc, sx, fx, n)); printf("Trapezoid: %f\n", trapezoidal_int(ourfunc, sx, fx, n)); return 0; }