/* * numerical integration example, as discussed in textbook: * * compute pi by approximating the area under the curve f(x) = 4 / (1 + x*x) * between 0 and 1. * * parallel version using MPI, as discussed in Appendix B. */ #include #include #include /* MPI header file */ #define NUM_STEPS 100000000 /* a short function to print a message, clean up, and exit */ void error_exit(char msg[]) { fprintf(stderr, "%s", msg); MPI_Finalize(); exit(EXIT_FAILURE); } /* main program */ int main(int argc, char *argv[]) { int nprocs; int myid; double start_time, end_time; int i; double x, pi; double sum = 0.0; double step = 1.0/(double) NUM_STEPS; /* initialize for MPI */ if (MPI_Init(&argc, &argv) != MPI_SUCCESS) { fprintf(stderr, "MPI initialization error\n"); return EXIT_FAILURE; } /* get number of processes */ MPI_Comm_size(MPI_COMM_WORLD, &nprocs); /* get this process's number (ranges from 0 to nprocs - 1) */ MPI_Comm_rank(MPI_COMM_WORLD, &myid); /* record start time */ start_time = MPI_Wtime(); /* do computation */ for (i=myid; i < NUM_STEPS; i += nprocs) { /* changed */ x = (i+0.5)*step; sum = sum + 4.0/(1.0+x*x); } sum = step * sum; /* changed */ MPI_Reduce(&sum, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);/* added */ /* record end time */ end_time = MPI_Wtime(); /* print results */ if (myid == 0) { printf("parallel program results with %d processes:\n", nprocs); printf("pi = %g (%17.15f)\n",pi, pi); printf("time to compute = %g seconds\n", end_time - start_time); } /* clean up for MPI */ MPI_Finalize(); return EXIT_SUCCESS; }