/* Jonathan Hauenstein - University of Notre Dame Center for Applied Mathematics Minicourse on Parallel Computing April 24, May 1, May 8, 2008 Sample programs are designed for educational use */ #include #include // computes the value of pi using a monte carlo integration int samples_in_circle(int num_samples); int main(int argc, char **argv) { int my_id, num_proc, num_points = 0, my_points, my_count, total; // initialize MPI MPI_Init(&argc, &argv); // find unique id MPI_Comm_rank(MPI_COMM_WORLD, &my_id); // find the number of processes running MPI_Comm_size(MPI_COMM_WORLD, &num_proc); if (my_id == 0) { // find the number of sample points that the user wants to use int points_per_proc = 0; printf("Please enter the number of sample points to use: "); scanf("%d", &num_points); // quick error checking if (num_points <= 0) { printf("The number of points was not read in properly. This program will terminate!\n\n"); MPI_Abort(MPI_COMM_WORLD, 1); } // split up the points equally between the other processors points_per_proc = num_points / num_proc; // find the number of points left over that will be computed on id 0 my_points = num_points - points_per_proc * (num_proc - 1); // tell everyone else how many points they need to use MPI_Bcast(&points_per_proc, 1, MPI_INT, 0, MPI_COMM_WORLD); } else { // recv the number of points it will need to use MPI_Bcast(&my_points, 1, MPI_INT, 0, MPI_COMM_WORLD); } // on each process, do the monte carlo integration based on the number of points that it has my_count = samples_in_circle(my_points); // collect the sum of the points in the circle on id 0 MPI_Reduce(&my_count, &total, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); if (my_id == 0) { // compute the approximation of pi double pi = (4.0 * total) / num_points; printf("\nUsing %d points, the approximation to pi is %.15f.\n\n", num_points, pi); } // finalize MPI MPI_Finalize(); return 0; }