#include "mpi.h" #include #include #include double maxlocdval(double *a, int l, int *p); int main( int argc, char *argv[]) { int my_rank, num_procs, root; MPI_Status status; int rc; double x, xmn=0.0, xmx=10.0, my_valmx; int my_locmx; const int MxFuncVals=10000; double *fvals; struct { double val; int pos; } inmx, outmx; int i, j, my_imn, my_imx, per_proc, my_flen; MPI_Init(&argc,&argv); MPI_Comm_rank(MPI_COMM_WORLD,&my_rank); MPI_Comm_size(MPI_COMM_WORLD,&num_procs); /* Define function and interval per each process */ // local dimensions: per_proc=(MxFuncVals+num_procs-1)/num_procs; my_imn=my_rank*per_proc; my_imx=(my_rank+1)*per_proc-1; if ( my_imx >= MxFuncVals ) my_imx = MxFuncVals-1; printf("In process %d my_imn, my_imx = %d, %d\n",my_rank,my_imn, my_imx); my_flen = (my_imx-my_imn+1); // local array: fvals=(double *)malloc(sizeof((double)1.0)*my_flen); if ( fvals == NULL ) { fprintf(stderr,"Process %d can't allocate FVALS(%d) !\n",my_rank,my_flen); } // function values: for ( i = my_imn; i <= my_imx; i++ ) { x=xmn+(xmx-xmn)*i/(MxFuncVals-1.0); j = i-my_imn; fvals[j] = (5.0-x)*sin(x*7.0)*cos(x*15.0); } /* ! Compute global maximum value and location */ // maximum value and location per each process: my_valmx=maxlocdval(fvals,my_flen,&my_locmx); my_locmx=my_imn+my_locmx; inmx.val = my_valmx; inmx.pos = my_locmx; // copy into buffer printf("In process %d my_valmx = %lf, my_locmx = %d\n",my_rank, inmx.val, inmx.pos); root=0; rc=MPI_Reduce( &inmx, &outmx, 1, MPI_DOUBLE_INT, MPI_MAXLOC, root, MPI_COMM_WORLD ); if ( rc != 0 ) { printf("For process %d MPI_Reduce = %d\n",my_rank,rc); } MPI_Barrier(MPI_COMM_WORLD); if ( my_rank == root ) { i=outmx.pos; x=xmn+(xmx-xmn)*i/(MxFuncVals-1.0); printf("Maximum value is %lf in x = %lf\n",outmx.val,x); } printf(" Bye bye from %d\n",my_rank); //free(fvals); MPI_Finalize(); return(0); } double maxlocdval(double *a, int l, int *p) { /* Compute maximum value and first location found in array a Input: double *a: array of values int l: array length Output: int *p: position of first occurrence of maximum value double maxlocdval(): maximum value found */ double vmx; int i; vmx = a[0]; *p=0; if ( l <= 1 ) return vmx; for ( i = 1; i < l; i++ ) { if ( vmx < a[i] ) { vmx = a[i]; *p=i; } } return vmx; }