1 /* -*- Mode: C; c-basic-offset:4 ; -*- */
2 /*
3 * (C) 2001 by Argonne National Laboratory.
4 * See COPYRIGHT in top-level directory.
5 */
6
7 #include "mpi.h"
8 #include <stdio.h>
9 #include <math.h>
10
11 double f(double);
12
f(double a)13 double f(double a)
14 {
15 return (4.0 / (1.0 + a*a));
16 }
17
main(int argc,char * argv[])18 int main(int argc,char *argv[])
19 {
20 int n, myid, numprocs, i;
21 double PI25DT = 3.141592653589793238462643;
22 double mypi, pi, h, sum, x;
23 double startwtime = 0.0, endwtime;
24 int namelen;
25 char processor_name[MPI_MAX_PROCESSOR_NAME];
26
27 MPI_Init(&argc,&argv);
28 MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
29 MPI_Comm_rank(MPI_COMM_WORLD,&myid);
30 MPI_Get_processor_name(processor_name,&namelen);
31
32 fprintf(stdout,"Process %d of %d is on %s\n",
33 myid, numprocs, processor_name);
34 fflush(stdout);
35
36 n = 10000; /* default # of rectangles */
37 if (myid == 0)
38 startwtime = MPI_Wtime();
39
40 MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
41
42 h = 1.0 / (double) n;
43 sum = 0.0;
44 /* A slightly better approach starts from large i and works back */
45 for (i = myid + 1; i <= n; i += numprocs)
46 {
47 x = h * ((double)i - 0.5);
48 sum += f(x);
49 }
50 mypi = h * sum;
51
52 MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
53
54 if (myid == 0) {
55 endwtime = MPI_Wtime();
56 printf("pi is approximately %.16f, Error is %.16f\n",
57 pi, fabs(pi - PI25DT));
58 printf("wall clock time = %f\n", endwtime-startwtime);
59 fflush(stdout);
60 }
61
62 MPI_Finalize();
63 return 0;
64 }
65