#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include "mpi.h"
int main(int argc,char* argv[])
{
long npoints ;
double circle_count = 0;
double sum_c = 0;
int myid, numprocs, name_length;
char procs_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
MPI_Get_processor_name(procs_name, &name_length);
MPI_Status status;
int i,j;
srand((int)time(0));
double x, y, pi, sum = 0.0, PII = 3.1415926535897932384643;
if(myid==0)
{
npoints = 1000000;
for (j = 1; j < numprocs; j++) {
MPI_Send(&npoints, 1, MPI_LONG, j, 0, MPI_COMM_WORLD);
}
}
else {
MPI_Recv(&npoints, 1, MPI_LONG, 0, 0, MPI_COMM_WORLD, &status);
}
for(i=myid;i<npoints;i+=numprocs)
{
x = rand() / (RAND_MAX +0.0);
y = rand() / (RAND_MAX +0.0);
if((x-1)*(x-1)+(y-1)*(y-1)<=1)
{
circle_count = circle_count + 1;
}
}
MPI_Reduce(&circle_count,&sum_c,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
if (myid == 0) {
pi = 4.0 * sum_c / npoints;
printf("%lf\n", pi);
printf("%lf", pi - PII);
}
MPI_Finalize();
return 0;
}