-
Notifications
You must be signed in to change notification settings - Fork 14
/
mpiSRpi.c
79 lines (66 loc) · 2.33 KB
/
mpiSRpi.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "mpi.h"
/* totally arbitrary seed for srand */
#define SEED 314159
int main(int argc, char* argv[])
{
long niter = 1000000;
int myid; //hold's process's rank id
int numnodes;
double x,y; //x,y value for the random coordinate
int i, count=0; //Count holds all the number of how many good coordinates
double z; //Used to check if x^2+y^2<=1
double pi; //holds approx value of pi
MPI_Status status;
MPI_Init(&argc, &argv); //Start MPI
MPI_Comm_rank(MPI_COMM_WORLD, &myid); //get rank of node's process
MPI_Comm_size(MPI_COMM_WORLD, &numnodes);
int counts[numnodes]; // contains all processes circle point counts
int temp; // temp buffer to store incoming count messages on node 0
/* Everyone needs a different seed or they'll get the same "random" sequence */
srand(SEED+myid);
/* Have everyone do the work, then have one node coordinate results */
for(i = 0; i < niter; i++)
{
x= ((double)rand())/RAND_MAX; //gets a random x coordinate
y =((double)rand())/RAND_MAX; //gets a random y coordinate
z = x*x+y*y; //Checks to see if number in inside unit circle
if (z<=1)
{
count++; //if it is, consider it a valid random point
}
}
// printf("I am node %d, my count was %d\n", myid, count);
if(myid != 0) /* Everyone sends their contribution to node 0 */
{
MPI_Send(&count, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
}
else /* Node 0 needs to receive a message from everyone else */
{
/* Put root's count in place */
counts[0] = count;
for(i = 0; i < numnodes-1; i++)
{
/* We don't know who will be done first, so we need to post an MPI_ANY_SOURCE receieve */
MPI_Recv(&temp, 1, MPI_INT, MPI_ANY_SOURCE, 1, MPI_COMM_WORLD, &status);
/* Find out who this MPI_Recv() message came from */
counts[status.MPI_SOURCE] = temp;
}
}
/* Ok, root has everyone's contributions; add them up and calculate Pi */
if (myid == 0)
{
int final = 0;
for(i = 0; i<numnodes; ++i)
{
final += counts[i];
}
long final_iters = numnodes*niter;
pi = ((double)final/(double)final_iters)*4.0; //p = 4(m/n)
printf("%d nodes over %d iterations calculated Pi as: %f\n", numnodes, final_iters, pi); //Print the calculated value of pi
}
MPI_Finalize(); //Close the MPI instance
return 0;
}