#include #include #define FALSE 0 #define TRUE 1 #define MASTER_RANK 0 double f(a) double a; { return (4.0 / (1.0 + a*a)); } int main ( int argc, char **argv ) { int n, i, pool_size, my_rank, i_am_the_master = FALSE; double mypi, pi, h, sum, x, a; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &pool_size); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); if (my_rank == MASTER_RANK) i_am_the_master = TRUE; if (i_am_the_master) { printf("Enter the number of intervals: "); scanf("%d",&n); if (n==0) n=100; } MPI_Bcast(&n, 1, MPI_INT, MASTER_RANK, MPI_COMM_WORLD); h = 1.0 / (double) n; sum = 0.0; for (i = my_rank + 1; i <= n; i += pool_size) { x = h * ((double)i - 0.5); sum += f(x); } mypi = h * sum; MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, MASTER_RANK, MPI_COMM_WORLD); if (i_am_the_master) printf("\npi is approximately %.16f\n", pi); MPI_Finalize (); }