//------------------------------------------------------------------- // traprule.cpp // // This program uses the Trapezoid Rule to compute a value for // the definite integral of a function f(x) from x=a to x=b. // // compile using: $ make traprule // execute using: $ traprule // // programmer: ALLAN CRUSE // written on: 19 SEP 2005 //------------------------------------------------------------------- #include // for printf(), perror() #include // for exp(), log(), sin(), cos(), etc double func( double x ) { double y = x*x; return y; } int main( int argc, char **argv ) { double a = 0.0, b = 1.0; int n = 10; double deltaX = (b - a)/n; printf( "\n\tNUMERICAL INTEGRATION USING TRAPEZOID RULE \n" ); printf( "\nIntegral is from a = %1.2f to b = %1.2f ", a, b ); printf( " with n = %d subintervals \n", n ); // show the function's value at each point-of-subdivision for (int i = 0; i <= n; i++) { double xi = a + i * deltaX; double yi = func( xi ); printf( "\n\tx%d\t%1.2f\t%1.6f", i, xi, yi ); } printf( "\n" ); // compute the integral's approximating sum by Trapezoid Rule double summation = 0.0; for (int i = 1; i < n; i+=2) { double xi = a + i * deltaX; double y0 = func( xi - deltaX ); double y1 = func( xi ); double y2 = func( xi + deltaX ); summation += (y0 + 2*y1 + y2); } double integral = (deltaX / 2)*summation; // display the result of the foregoing computation printf( "\nThe integral is approximately %1.6f \n\n", integral ); }