/* $Id: pi-mpi.c 812 2006-06-09 10:19:01Z olau $ */

#include <stdio.h>
#include <mpi.h>
#include <math.h>
#include "../../globaldefs.h"

#define ROOT                (0)

int main(int argc, char *argv[]) {
  int i;
  double w, x, sum, globalsum, pi;
  double t;
  int myrank, size;

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

  printf("Dies ist Job %2d von %2d\n", myrank, size);

  t = MPI_Wtime();
  w = 1.0 / DEFAULT_ITERATIONS;
  sum = 0.0;
  for (i = myrank + 1; i <= DEFAULT_ITERATIONS; i += size) {
    x = w * ((double) i - 0.5);
    sum += f(x);
  }
  MPI_Reduce(&sum, &globalsum, 1, MPI_DOUBLE, MPI_SUM, ROOT, MPI_COMM_WORLD);
  if (myrank == ROOT) {
    pi = w * globalsum;
    printf("pi = %.13lf (Fehler = %.13lf)\n", pi, pi - PI);
    printf("Ausfuehrungsdauer: %.2lf ms\n\n", 1000 * (MPI_Wtime() - t));
  }

  MPI_Finalize();
  return 0;
}
