DAPPLE Example: pi

Source code:

// pi -- a parallel program to compute pi // written using the Data-Parallel Programming Library for Education (DAPPLE) // // We compute pi as the integral of 4 / (1 + x^2) for x from 0 to 1. // we do this by using the rectangle rule to approximate the integral. // All function values can be computed in parallel, then sum-reduced. // // David Kotz 1994 // $Id: pi.cc,v 1.6 95/02/21 18:12:06 dfk CS15 Locker: dfk $ #include #include #include #include "dapple.h" // we divide the x range up into N intervals, computing the function at N points const int N = 1000; // which VP am I? useful for VP-specific math const intVector VP(N, Identity); int main(int argc, char **argv) { const double width = 1.0 / N; // width of each interval doubleVector X(N), Y(N); // X points, Y=f(X) // we compute pi as the integral of 4 / (1 + x^2) for x from 0 to 1 // we do this by using the rectangle rule to approximate the integral X = (floatVector(VP) + 0.5) * width; // find the midpoint of each interval Y = 4.0 / (1.0 + X * X); // compute the function there // sum the area of each rectangle (Y is the height of the rectangle) cout << "pi ~= " << sum (width * Y) << endl; return(0); }

Demonstration:

pi pi ~= 3.14159