Commits

Lisandro Dalcin committed b55f546

Add C and F90 versions for example 6a

  • Participants
  • Parent commits 68f338a

Comments (0)

Files changed (3)

File exercises/ex6a.c

+/* $ mpicc ex6a.cxx -o ex6a.exe */
+
+#include <mpi.h>
+
+int main(int argc, char *argv[])
+{
+  int myrank, nprocs;
+  int n, i;
+  double h, s, pi;
+  MPI_Comm master;
+
+  MPI_Init(&argc, &argv);
+
+  MPI_Comm_get_parent(&master);
+  MPI_Comm_size(master, &nprocs);
+  MPI_Comm_rank(master, &myrank);
+
+  MPI_Bcast(&n, 1, MPI_INT, 0, master);
+
+  h = 1.0 / (double) n;
+  s = 0.0;
+  for (i = myrank+1; i < n+1; i += nprocs) {
+    double x = h * (i - 0.5);
+    s += 4.0 / (1.0 + x*x);
+  }
+  pi = s * h;
+
+  MPI_Reduce(&pi, MPI_BOTTOM, 1, MPI_DOUBLE,
+             MPI_SUM, 0, master);
+
+  MPI_Comm_disconnect(&master);
+
+  MPI_Finalize();
+  return 0;
+}

File exercises/ex6a.f90

+! $ mpif90 ex6a.cxx -o ex6a.exe 
+
+PROGRAM main
+
+  USE mpi
+  implicit none
+
+  integer ierr
+  integer n, i, master, myrank, nprocs
+  real (kind=8) h, s, x, cpi
+
+  call MPI_INIT(ierr)
+  call MPI_COMM_GET_PARENT(master, ierr)
+  call MPI_COMM_SIZE(master, nprocs, ierr)
+  call MPI_COMM_RANK(master, myrank, ierr)
+
+  call MPI_BCAST(n, 1, MPI_INTEGER, &
+                 0, master, ierr)
+
+  h = 1 / DFLOAT(n)
+  s = 0.0
+  DO i=myrank+1,n,nprocs
+     x = h * (DFLOAT(i) - 0.5)
+     s = s +  4.0 / (1.0 + x*x)
+  END DO
+  cpi = s * h
+
+  call MPI_REDUCE(cpi, MPI_BOTTOM, 1, MPI_DOUBLE_PRECISION, &
+                  MPI_SUM, 0, master, ierr)
+
+  call MPI_COMM_DISCONNECT(master, ierr)
+  call MPI_FINALIZE(ierr)
+
+END PROGRAM main

File exercises/ex6a.py

 
 PI = numpy.array(0.0, 'd')
 worker.Reduce(None, [PI, MPI.DOUBLE],
-            op=MPI.SUM, root=MPI.ROOT)
+              op=MPI.SUM, root=MPI.ROOT)
 
 worker.Disconnect()