/******************************************************************************* * This is a simple program that shows the numerical integration example. * It computes pi by approximating the area under the curve: * f(x) = 4 / (1+x*x) between 0 and 1. * To do this intergration numerically, the interval from 0 to 1 is divided into * some number (num_sub_intervals) subintervals and added up the area of * rectangles * The larger the value of the num_sub_interval the more accurate your result * will be. * * The program first asks the user to input a value for subintervals, it * computes * the approximation for pi, and then compares it to a more accurate aproximate * value of pi in the math.h library. * * This program is just a serial version. * * Author: Mobeen Ludin * * How to Compile: * $ * * * ******************************************************************************/ #include #include #include #include #include int main(int argc, char *argv[]) { int num_sub_intervals = 0; double start_time, end_time, time_diff; double x, pi, pi_tot; double sum = 0.0; double step; int i; int r; int work; int low; int high; // MPI Initialization part int pRank, pNum; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &pNum); MPI_Comm_rank(MPI_COMM_WORLD, &pRank); if(pRank == 0){ printf("Please enter the number of iterations used to compute pi: \n"); scanf("%d", &num_sub_intervals); } //Sending the number of sub intervals to all process in the communicator MPI_Bcast(&num_sub_intervals, 1, MPI_INT, 0, MPI_COMM_WORLD); step = 1.0/(double) num_sub_intervals; // Record the start time from here on: start_time = MPI_Wtime(); for(i=pRank+1; i<=num_sub_intervals; i+=pNum){ x = step*((double)i-0.5); sum += 4.0/(1.0+x*x); } pi = step * sum; MPI_Reduce(&pi, &pi_tot, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); //End recording the time here. end_time = MPI_Wtime(); time_diff = end_time - start_time; if(pRank == 0){ // print the result here: printf("computed pi value is = %g (%17.15f)\n\n", pi_tot,pi_tot); printf("M_PI accurate value from math.h is: %17.15f \n\n", M_PI); printf("Difference between computed pi and math.h M_PI = %17.15f\n\n", fabs(pi_tot - M_PI)); printf("Time to compute = %g seconds\n\n", time_diff); } MPI_Finalize(); return EXIT_SUCCESS; }