next up previous index
Next: Exercise Up: Fortran Interface Previous: Greetings, Master

Dividing the Pie

gustav@sp21:../MPI 19:14:39 !667 $ cat pie.f
PROGRAM pie

  IMPLICIT NONE
  INCLUDE 'mpif.h'

  INTEGER :: ierror, pool_size, my_rank, n, i
  INTEGER, PARAMETER :: master_rank = 0
  LOGICAL :: i_am_the_master = .FALSE.
  REAL(kind=8) :: h, sum, x, my_pi, pi

  CALL mpi_init(ierror)
  CALL mpi_comm_size(MPI_COMM_WORLD, pool_size, ierror)
  CALL mpi_comm_rank(MPI_COMM_WORLD, my_rank, ierror)

  IF (my_rank == master_rank) i_am_the_master = .TRUE.

  IF (i_am_the_master) THEN
     WRITE(*,*) 'Enter the number of intervals: '
     READ(*,*) n
     IF (n .EQ. 0) n = 100
  END IF

  CALL mpi_bcast(n, 1, MPI_INTEGER, master_rank, MPI_COMM_WORLD, ierror)

  h = 1.0_8 / n
  sum = 0.0_8
  DO i = my_rank + 1, n, pool_size
     x = h * (i - 0.5_8)
     sum = sum + f(x)
  END DO
  my_pi = h * sum

  CALL mpi_reduce(my_pi, pi, 1, MPI_DOUBLE_PRECISION, MPI_SUM, &
       master_rank, MPI_COMM_WORLD, ierror)

  IF (i_am_the_master) WRITE(*,*) 'pi is approximately ', pi

  CALL mpi_finalize(ierror)

CONTAINS

  FUNCTION f(x)
    REAL(kind=8) :: f, x

    f = 4.0_8 / (1.0_8 + x * x)

  END FUNCTION f

END PROGRAM pie
gustav@sp21:../MPI 19:15:16 !668 $ mpxlf90 -o pie pie.f
** pie   === End of Compilation 1 ===
1501-510  Compilation successful for file pie.f.
gustav@sp21:../MPI 19:15:39 !669 $ poe ./pie -procs 8
 Enter the number of intervals: 
100000
 pi is approximately  3.14159265359813444
gustav@sp21:../MPI 19:16:02 !670 $



Zdzislaw Meglicki
2001-02-26