-
-
Save cristaloleg/5470fdd657d728c051da to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <mpi.h> | |
int main(int argc, char **argv) | |
{ | |
double precision = 1000000000; | |
int myrank, proccount; | |
double pi, pi_final; | |
int mine, sign; | |
int i; | |
// Initialize MPI | |
MPI_Init(&argc, &argv); | |
// find out my rank | |
MPI_Comm_rank(MPI_COMM_WORLD, &myrank); | |
// find out the number of processes in MPI_COMM_WORLD | |
MPI_Comm_size(MPI_COMM_WORLD, &proccount); | |
// now distribute the required precision | |
if (precision < proccount) { | |
printf("Precision smaller than the number of processes - try again."); | |
MPI_Finalize(); | |
return -1; | |
} | |
// each process performs computations on its part | |
pi = 0; | |
int count = precision / proccount; | |
if(myrank == proccount - 1) { | |
count += precision % proccount; | |
} | |
mine = count * myrank * 2 + 1; | |
sign = (((mine - 1) / 2) % 2) ? -1 : 1; | |
for(i = 0; i < count; ++i) { | |
pi += sign / (double)mine; | |
mine += 2; | |
sign = (((mine - 1) / 2) % 2) ? -1 : 1; | |
} | |
// now merge the numbers to rank 0 | |
MPI_Reduce(&pi, &pi_final, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); | |
if (!myrank) { | |
pi_final *= 4; | |
printf("pi=%f", pi_final); | |
} | |
// Shut down MPI | |
MPI_Finalize(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment