#include #include #include // MPI include file int main( int argc, char *argv[]) /* ! piArea.f90 - compute pi by counting random points in circle and ! circumscribing square. ! The circle has centre in the origin and radius 1 ! ! ! Each process: ! 1) receives the number of rectangles used in the approximation ! 2) generates and count points in rectangle and circle ! 3) Synchronizes for a global summation. ! Process 0 prints the result. ! ! Variables: ! ! pi the calculated result ! n number of random points ! x1, x2 extremes of each rectangle ! SqPoints points in each rectangle ! CiPoints points in circle ! */ { int done = 0, n, myid, numprocs, i; double PI25DT = 3.141592653589793238462643; double mypi, pi, h; double x, y, x1, x2, y1, y2; int SqPoints, CiPoints, my_SqPoints, my_CiPoints; double startwtime = 0.0, endwtime; int namelen; // MPI initialization: define numprocs and myid numprocs = 1; myid = 0; fprintf(stderr,"Process %d alive\n",myid); n = 0; while (!done) { if (myid == 0) { printf("Enter the number of points: (0 quits) \n"); scanf("%d",&n); } // Send number of points to all processes if (n <= 0) done = 1; else { h = 2.0 / (double) numprocs; x1 = -1.0 + myid * h; x2 = x1 + h; y1 = -1.0; y2 = 1.0; my_SqPoints = 0; my_CiPoints = 0; for (i = 1; i <= n; i += numprocs) { x = rand(); x = x / RAND_MAX; x = x1 + x * (x2 - x1); y = rand(); y = y / RAND_MAX; y = y1 + y * (y2 - y1); my_SqPoints++; if ( sqrt( x*x + y*y ) <= 1.0 ) my_CiPoints++; } // Sum up SqPoints from all processes: result in SqPoints // Sum up CiPoints from all processes: result in CiPoints SqPoints = my_SqPoints; CiPoints = my_CiPoints; if (myid == 0) { pi = 4.0 * (double)CiPoints / (double)SqPoints; printf("pi is approximately %.16f, Error is %.16f\n", pi, fabs(pi - PI25DT)); } } } // MPI finalization return 0; }