File: cpi%2B%2B.C

package info (click to toggle)
mpich 1.1.0-3
  • links: PTS
  • area: main
  • in suites: hamm
  • size: 22,116 kB
  • ctags: 27,349
  • sloc: ansic: 193,435; sh: 11,172; fortran: 6,545; makefile: 5,801; cpp: 5,020; tcl: 3,548; asm: 3,536; csh: 1,079; java: 614; perl: 183; awk: 168; sed: 70; f90: 62
file content (63 lines) | stat: -rw-r--r-- 1,230 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
 * $Id: cpi++.C,v 1.2 1996/03/08 21:02:41 gropp Exp $
 */

#include <mpi++.h>
#include <stdio.h>
#include <math.h>

double f(double a)
{
    return (4.0 / (1.0 + a*a));
}

int main(int argc, char *argv[])
{
   int done = 0, n, myid, numprocs, i, rc;
   double PI25DT = 3.141592653589793238462643;
   double mypi, pi, h, sum, x, a;
   double startwtime, endwtime;

   MPI_COMM_WORLD.Init (argc, argv);
   MPI_COMM_WORLD.Rank (myid) ;
   MPI_COMM_WORLD.Size (numprocs) ;
 
   while (!done)
   {
	 if (myid == 0)
     {
	   printf("Enter the number of intervals: (0 quits) ");
	   scanf("%d",&n);
	   startwtime = MPI_Wtime();
	 }
	 MPI_COMM_WORLD.Bcast(&n, 1, MPI_INT, 0);
	 if (n == 0)
	   done = 1;
	 else
     {
	   h   = 1.0 / (double) n;
	   sum = 0.0;
	   for (i = myid + 1; i <= n; i += numprocs)
	   {
		 x = h * ((double)i - 0.5);
		 sum += f(x);
	   }
	   mypi = h * sum;
	   
	   MPI_COMM_WORLD.Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0);
 
	   if (myid == 0)
       {
		 printf("pi is approximately %.16f, Error is %.16f\n",
				pi, fabs(pi - PI25DT));
		 endwtime = MPI_Wtime();
		 printf("wall clock time = %f\n",
				endwtime-startwtime);
	   }
	 }
   }

  MPI_COMM_WORLD.Finalize();
  return (MPI_SUCCESS);
}