/* line_int.c integrate a function over a line */ /* this is numerical quadrature */ /* basically compute an area under line function */ /* compare methods for accuracy */ /* first trapezoid rule, varying step size, int f(x) dx */ /* then using Gauss-Legendre coordinates and weights */ /* remember np points or nodes means np-1 intervals or segments */ /* np will be the number of times the function is computed */ #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) { return x+2.0; /* linear */ } static double f2(double x) { return x*x + 2.0*x + 3.0; /* quadratic, second order */ } static double f3(double x) { return x*x*x + 2.0*x*x + 3.0*x + 4.0; /* cubic, third order */ } static double fe(double x) { return exp(x); } int main(int argc, char *argv[]) { /* simple trapezoidal integration from x=1 to x=3*/ double area, sum; double x, h; double xmin = 1.0; double xmax = 3.0; double f1exact = 8.0; double f2exact = 68.0/3.0; double f3exact = 57.0+1.0/3.0; double feexact; double xx[200], ww[200]; /* for Gauss-Legendre */ double val; int p, np; int i, j; feexact = exp(xmax)-exp(xmin); printf("line_int.c integrate to find area \n"); printf("Numerical quadrature, x=%g to x=%g \n", xmin, xmax); printf("\n"); printf("Using trapezoidal method \n"); np = 4; h = (xmax-xmin)/(double)(np-1); printf("f1(x)=x+2.0 np=%d, h=%g \n", np, h); area = (f1(xmin) + f1(xmax))/2.0; for(i=1; i