int main(int argc, char *argv[]) { int my_rank; int p; float a = 0.0; float b = 1.0f; int n = 1024; float h; float local_a; float local_b; int local_n; float integral; float total; int source; int dest = 0; int tag = 0; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &p); Get_data2(&a, &b, &n, my_rank); h = (b - a) / n; local_n = n / p; local_a = a + my_rank* local_n * h; local_b = local_a + local_n * h; integral = Trap(local_a, local_b, local_n, h); if (my_rank == 0) { total = integral; for (source = 1; source < p; source++) { MPI_Recv(&integral, 1, MPI_FLOAT, source, tag, MPI_COMM_WORLD, &status); total = total + integral; } } else { MPI_Send(&integral, 1, MPI_FLOAT, dest, tag, MPI_COMM_WORLD); } if (my_rank == 0) { printf("With n = %d trapezoids, our estimate\n", n); printf("of the integral from %f to %f = %f\n", a, b, total); } MPI_Finalize(); }
int main(int argc, char** argv){ int my_rank; int p; float a = 0.0; float b = 1.0; int n = 1024; float h; float local_a; float local_b; int local_n; float integral; float total; int source = 0; int dest = 0; int tag = 0; int f; MPI_Status status; float (*functions[2]) (float x); float Trap(float local_a, float local_b, int local_n, float h, float (*f)(float)); functions[0] = square; functions[1] = cube; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &p); if ( my_rank == 0){ printf("Integrate 0. Squared - 1.Cubed\n"); scanf("%d",&f); for(dest = 1;dest <p; dest++) MPI_Send( &f, 1, MPI_FLOAT, dest, tag, MPI_COMM_WORLD); } else{ MPI_Recv( &f, 1, MPI_FLOAT, 0, tag, MPI_COMM_WORLD, &status); } #if TREE_COMMUNICATE Get_data1( &a, &b,&n, my_rank, p); #elif BROADCAST Get_data2( &a, &b,&n, my_rank); #else Get_data( &a, &b,&n, my_rank, p); #endif h = (b-a)/n; local_n = n/p; local_a = a + my_rank*local_n*h; local_b = local_a + local_n*h; integral = Trap(local_a, local_b, local_n, h, functions[f]); #if REDUCE MPI_Reduce(&integral, &total, 1, MPI_FLOAT, MPI_SUM, 0, MPI_COMM_WORLD); #else if( my_rank == 0){ total = integral; for ( source = 1; source < p; source ++){ MPI_Recv(&integral,1, MPI_FLOAT, source, tag, MPI_COMM_WORLD, &status); total = total + integral; } } else{ MPI_Send(&integral, 1, MPI_FLOAT,dest, tag, MPI_COMM_WORLD); } #endif if (my_rank == 0){ printf("With n == %d trapezoids, our estimate \n",n); printf("of the integral from %f to %f == %f \n",a,b,total); } MPI_Finalize(); return 0; }