Page MenuHomec4science

pi_gather.f90
No OneTemporary

File Metadata

Created
Wed, Sep 11, 03:09

pi_gather.f90

! ==========================================================================
! This exercise is taken from the class Parallel Programming Workshop (MPI,
! OpenMP and Advanced Topics) at HLRS given by Rolf Rabenseifner
! ==========================================================================
program pi_reduction
use mpi
implicit none
integer, parameter :: n = 10000000
double precision :: omp_t1, omp_t2
double precision :: dx, x, sm, pif
double precision, external :: f
double precision, allocatable, dimension(:) :: sms
integer :: i
integer :: ierror, prank, psize
integer :: nlocal, istart, iend
call MPI_init(ierror)
call MPI_Comm_size(MPI_COMM_WORLD, psize, ierror)
call MPI_Comm_rank(MPI_COMM_WORLD, prank, ierror)
! calculate pi = integral [0..1] 4 / (1 + x**2) dx
omp_t1 = MPI_Wtime()
nlocal = n / psize
istart = 1 + nlocal * prank
iend = nlocal * (prank + 1);
dx = 1. / n
sm = 0.0;
do i = istart, iend
x = (1. * i - 0.5) * dx
sm = sm + f(x)
enddo
allocate(sms(psize))
if (prank.eq.0) then
call MPI_Gather(sm, 1, MPI_DOUBLE, sms, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD, ierror)
sm = 0.
do i = 1, psize
sm = sm + sms(i)
enddo
else
call MPI_Gather(sm, 1, MPI_DOUBLE, sms, 0, MPI_DOUBLE, 0, MPI_COMM_WORLD, ierror);
endif
call MPI_Bcast(sm, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD, ierror);
pif = dx * sm
omp_t2 = MPI_Wtime()
if (prank.eq.0) then
print *, 'computed pi =',pif
print *, 'Running time = ', (omp_t2-omp_t1)
endif
deallocate(sms)
call MPI_Finalize(ierror)
end program pi_reduction
double precision function f(a)
implicit none
double precision, intent(in) :: a
f = 4. / (1. + (a**2))
end function f

Event Timeline