#include<stdio.h>
#include<mpi.h>
#include<math.h>
long n,
i;
double sum,
pi,
mypi,
x,
h;
int group_size,my_rank;
int main(argc,argv)
int argc;
char *argv[];
{
int group_size,my_rank;
MPI_Status status;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
MPI_Comm_size(MPI_COMM_WORLD,&group_size);
n=20;
MPI_Bcast(&n,1,MPI_LONG,0,MPI_COMM_WORLD);
h=1.0/(double)n;
sum=0.0;
for(i=my_rank+1;i<=n;i+=group_size)
{
printf("i=%ld,processor=%d\n",i,my_rank);
x=h*(i-0.5);
sum=sum+4.0/(1.0+x*x);
}
mypi=h*sum;
printf("the rank %ld,calculate mypi=%lf\n",my_rank,mypi);
MPI_Reduce(&mypi,&pi,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
if(0==my_rank)
printf("pi is :%lf\n",pi);
fflush(stdout);
MPI_Finalize();
return 0;
}
In order calculate pi
1)Every processor calculate part of pi
Then use MPI_Reduce() to sum all of each part
see the code above
2) If we remove the clause:if(0==my_rank), what will happen?
We see that each clause was run 4 times, and only when my_rank equal to 0, pi=3.14 otherwise it equals to 0.00!
any question?