#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
#include <math.h>
/*
** start of main
*/
int main(int argc, char *argv[])
{
int niter = 100000000;
double x, y;
int i, j, count = 0, mycount;
double z, pi, z1;
int nproc, nrank, proc;
MPI_Status status;
int master = 0;
int tag = 123;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nproc);
MPI_Comm_rank(MPI_COMM_WORLD, &nrank);
mycount = 0;
srand(time(NULL)*nrank);
for (i=0; i
{
x = (double)rand() / (double)(RAND_MAX);
y = (double)rand() / (double)(RAND_MAX);
z = x*x + y*y;
if (z <= 1) mycount++;
}
/*
** master : nrank = 0
*/
if (nrank == 0)
{
count = mycount;
for (proc=1; proc
{
MPI_Recv(&mycount, 1, MPI_REAL, proc, tag, MPI_COMM_WORLD, &status);
count += mycount;
}
pi = (double)4*count/(niter*nproc);
printf("Processor %d sending results = %d to master process\n", nrank, mycount);
printf("\n # of trials (cpu#: %d, time#: %d) = %d, estimate of pi is %g\n .", nproc, niter, niter*nproc, pi);
}
else {
printf("Processor %d sending results = %d to master process\n", nrank, mycount);
MPI_Send(&mycount, 1, MPI_REAL, master, tag, MPI_COMM_WORLD);
}
MPI_Finalize();
return 0;
}
|