/* 05_pi_collective.c - compute pi by numerical integration of 4/(1+x^2) on [0,1].
 * Rank 0 reads the number of intervals, MPI_Bcast shares it, every rank integrates
 * its share of the intervals, and MPI_Reduce adds the partial sums on rank 0.
 * Build: mpicc -O2 -o 05_pi_collective 05_pi_collective.c -lm
 * Run:   mpirun -np 4 ./05_pi_collective 100000000
 */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <mpi.h>

int main(int argc, char **argv)
{
    const double PI25DT = 3.141592653589793238462643;
    int rank, size;
    long n = 0;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    if (rank == 0) n = (argc > 1) ? atol(argv[1]) : 10000000;
    MPI_Bcast(&n, 1, MPI_LONG, 0, MPI_COMM_WORLD);        /* everyone now knows n */

    double t0 = MPI_Wtime();
    double h = 1.0 / (double)n, sum = 0.0;
    for (long i = rank + 1; i <= n; i += size) {           /* cyclic distribution */
        double x = h * ((double)i - 0.5);
        sum += 4.0 / (1.0 + x * x);
    }
    double mypi = h * sum, pi = 0.0;
    MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
    double elapsed = MPI_Wtime() - t0;

    if (rank == 0)
        printf("n = %ld, processes = %d: pi = %.16f, error = %.2e, time = %.3f s\n",
               n, size, pi, fabs(pi - PI25DT), elapsed);

    MPI_Finalize();
    return 0;
}
