program mypi implicit none c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% c%%%%% MPI declarations include 'mpif.h' integer nproc, rank, p, ierr, rc c%%%%% problem declarations integer myn,n, istart, iend double precision h,s,x,glob_pi integer i c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% c%%%% start MPI c23456 call MPI_INIT(ierr) if (ierr .ne. MPI_SUCCESS) then print *,'Error starting MPI program. Terminating.' call MPI_ABORT(MPI_COMM_WORLD, rc, ierr) end if c%%%% what is my number (rank+1) and total number of processors call MPI_COMM_RANK(MPI_COMM_WORLD, rank, ierr) call MPI_COMM_SIZE(MPI_COMM_WORLD, nproc, ierr) c p = rank + 1 if (rank.eq.0) then write(6,*) 'Number of processors=',nproc endif c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% c%%%%% actual algorithm c%%%% set size of subproblem as a constant myn = 100 n = nproc * myn c%%% h = 1.D0/n c%%% compute the integral using midpoint rule s = 0D0 c%%% istart = rank*myn + 1 iend = p*myn do i = istart, iend x = i*h - h/2D0 s = s + 1D0 / (1D0+x*x) enddo s = s * 4.D0 * h write(6,*) 'My partial result for proc =',p,' is=',s c %%% PARALLEL: must add all values call MPI_REDUCE(s,glob_pi,1,MPI_DOUBLE_PRECISION,MPI_SUM,0, $ MPI_COMM_WORLD,ierr) c %%% finished if (rank.eq.0) then write(6,*) 'Finished with ',n,' subitervals. Result=',glob_pi write(6,*) 'Error = ',abs( glob_pi-atan(1.0)*4D0 ) endif c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% call MPI_FINALIZE(ierr) end