#include "mpi.h"
#include <cstdio>
#include <cstdlib>
#include <cmath>
int main(int argc, char *argv[]) {
long double acc = 0.0;
long double pi = 0.0;
long double real_pi = 3.1415926535897932384626433832795028841971693993751058209749;
MPI_Init(&argc, &argv);
int rank, size;
const int MASTER = 0, TAG = 0;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
__int64 nIter = 10000000000 / size;
long double start = MPI_Wtime();
for (__int64 k = rank * nIter; k < nIter * (1 + rank); k++) {
acc += 4 * (k % 2 == 0 ? 1.0 : -1.0) / (2.0 * k + 1);
}
printf("Calculated part = %.16f in %d process\n", acc, rank);
if (rank == 0) {
for (int i = 1; i < size; i++) {
MPI_Status status;
long double tmp = 0.0;
MPI_Recv(&tmp, 1, MPI_LONG_DOUBLE, i, TAG, MPI_COMM_WORLD, &status);
acc += tmp;
}
pi = acc;
long double end = MPI_Wtime();
printf("Calculated pi = %0.16f with %i processes in %f\n", pi, size, end - start);
} else {
MPI_Send(&acc, 1, MPI_LONG_DOUBLE, MASTER, TAG, MPI_COMM_WORLD);
}
MPI_Finalize();
return EXIT_SUCCESS;
}