/* rect_int.c integrate a function over a rectangle */ /* this is numerical quadrature */ /* basically compute a volume under surface function*/ /* compare methods for accuracy */ /* first trapezoid rule, varying step size, int f(x,y) dx dx */ /* then using Gauss-Legendre coordinates and weights */ /* remember np points or nodes means np*np function evaluations */ /* or (np-1)*(np-1) rectangular elements */ #include #include #undef abs #define abs(x) ((x)<0.0?(-(x)):(x)) static void gaulegf(double x1, double x2, double x[], double w[], int n); static double f1(double x, double y) { return x+2.0*y+3.0; /* linear, first order */ } static double f2(double x, double y) { return x*x+2.0*y*y+3.0*x*y+4.0*x+5.0*y+6.0; /* quadratic, second order */ } static double f3(double x, double y) { return x*x*x + 2.0*y*y*y + 3.0*x*x*y + 4.0*y*y*x + 5.0*x*x + 6.0*y*y + 7.0*x*y + 8.0*x + 9.0*y + 10.0; /* cubic, third order */ } static double fe(double x, double y) { return exp(x)*exp(y); } int main(int argc, char *argv[]) { /* simple trapezoidal integration from x=1 to x=3*/ double volume; double x, y, hx, hy; double xmin = 1.0; double xmax = 3.0; double ymin = 0.5; double ymax = 2.0; double f1exact = 22.5; double f2exact = 106.75; double f3exact = 397.4375; double feexact = 99.69385929; double xx[200], wx[200]; /* for Gauss-Legendre */ double yy[200], wy[200]; /* for Gauss-Legendre */ int i, j, np; printf("rect_int.c integrate to find volume \n"); printf("Numerical quadrature, x=%g to x=%g, y=%g to y=%g \n", xmin, xmax, ymin, ymax); printf("\n"); printf("Using trapezoidal method \n"); np = 4; hx = (xmax-xmin)/(double)(np-1); hy = (ymax-ymin)/(double)(np-1); printf("f1(x,y)=x+2y+3 np=%d, hx=%g, hy=%g \n", np, hx, hy); volume = 0.0; for(i=0; i