DAPPLE Example: trapezoid

Source code:

// @TITLE "trapezoid.cc -- parallel trapezoid rule" // // trapezoid -- a parallel trapezoid-rule integration program // written using the Data-Parallel Programming Library for Education (DAPPLE) // // We integrate a function by using the trapezoid rule, computing all // function values in parallel. // Note that the function f(x) is defined as a vector function so that // many values can be computed (for different x values) in parallel, // with Y = f(X). Otherwise, with a plain f(x) function, it could have // been written Y = apply(f, X). // // David Kotz 1994 // $Id: trapezoid.cc,v 1.5 94/09/29 12:19:23 dfk Exp Locker: dfk $ #include #include #include #include "dapple.h" // we divide the x range up into N intervals, computing the function at N+1 points const int N = 100; // which VP am I? useful for VP-specific math const intVector VP(N+1, Identity); inline doubleVector f(const doubleVector& x) { return x*x - 10; } int main(int argc, char **argv) { const double a = -5; // bounds of the integration const double b = 50; double h = (b-a) / N; // interval size doubleVector X(N+1), Y(N+1); double integral; X = a + doubleVector(VP) * h; // compute the x coordinates Y = f(X); // evaluate the function at all those points ifp ((VP == 0) || (VP == N)) Y /= 2; // halve the endpoints // add them up and multiply by h... integral = h * sum(Y); cout << "integral is " << integral << endl; return(0); }

Demonstration:

trapezoid integral is 41161.1