JSU Course 2005 Homework 2 Answer

/*--------------------------------------------*/
/* Saleh Elmohamed  1996. Geoffrey Fox 2005                    */
/* Modified 2005 from http://www.old-npac.org/projects/cpsedu/summer98summary/examples/mpi-c/examples96/simpson-rule_with_mpi.c */
/*--------------------------------------------*/

/* Note this example does not treat A sensibly; it would be best to
only have part of A stored on each processor */

#include  <stdio.h>
#include  <math.h>
#include  <mpi.h>


#define N 1000                   /* Number of sum values in each processor */


void main(int argc, char *argv[])
{
  int Procs;                   /* Number of processors */
  int my_rank;                 /* Processor number */ 
  double  sum,total,processor_output_share[100], A[100000];
  int i,i1;
  MPI_Status status;
  
                               /* Let the system do what it needs to start up MPI */
  MPI_Init(&argc, &argv);
                               /* Get my process rank */
  MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
                               /* Find out how many processes are being used. */
  MPI_Comm_size(MPI_COMM_WORLD, &Procs);
  
                               /* Each processor computes its partial sum */

  sum = 0.0;
  i1 = my_rank*N;
  for(i = 0; i < N ; i++)
    {
      sum += A[i+i1];
     }

                               /* Add up the sums calculated by each processor. */
  if(my_rank == 0)
    {
      processor_output_share[0] = sum;
                               /* source = i, tag = 0 */
      for(i = 1; i < Procs; i++)
	MPI_Recv(&(processor_output_share[i]), 1, MPI_DOUBLE, i, 0, MPI_COMM_WORLD, &status);
    }
  else
    {
                               /* dest = 0, tag = 0 */
      MPI_Send(&sum, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
    }
                               /* Add up the value of sum and print the result.  */
  if(my_rank == 0)
    {
      total = 0.0;
      for(i = 0; i < Procs; i++)
	total += processor_output_share[i];
      printf("-------------------------------------------------\n");
      printf("The computed Total of the integral for %d  points is  %25.16e \n",
	     (N * Procs), total);

 }
  MPI_Finalize();
}