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 /* This is an interactive version of cpi */
8 #include "mpi.h"
9 #include <stdio.h>
10 #include <math.h>
11
12 double f(double);
13
f(double a)14 double f(double a)
15 {
16 return (4.0 / (1.0 + a*a));
17 }
18
main(int argc,char * argv[])19 int main(int argc,char *argv[])
20 {
21 int done = 0, n, myid, numprocs, i;
22 double PI25DT = 3.141592653589793238462643;
23 double mypi, pi, h, sum, x;
24 double startwtime = 0.0, endwtime;
25 int namelen;
26 char processor_name[MPI_MAX_PROCESSOR_NAME];
27
28 MPI_Init(&argc,&argv);
29 MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
30 MPI_Comm_rank(MPI_COMM_WORLD,&myid);
31 MPI_Get_processor_name(processor_name,&namelen);
32
33 /*
34 fprintf(stdout,"Process %d of %d is on %s\n",
35 myid, numprocs, processor_name);
36 fflush(stdout);
37 */
38
39 while (!done) {
40 if (myid == 0) {
41 fprintf(stdout, "Enter the number of intervals: (0 quits) ");
42 fflush(stdout);
43 if (scanf("%d",&n) != 1) {
44 fprintf( stdout, "No number entered; quitting\n" );
45 n = 0;
46 }
47 startwtime = MPI_Wtime();
48 }
49 MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
50 if (n == 0)
51 done = 1;
52 else {
53 h = 1.0 / (double) n;
54 sum = 0.0;
55 for (i = myid + 1; i <= n; i += numprocs) {
56 x = h * ((double)i - 0.5);
57 sum += f(x);
58 }
59 mypi = h * sum;
60 MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
61
62 if (myid == 0) {
63 printf("pi is approximately %.16f, Error is %.16f\n",
64 pi, fabs(pi - PI25DT));
65 endwtime = MPI_Wtime();
66 printf("wall clock time = %f\n", endwtime-startwtime);
67 fflush( stdout );
68 }
69 }
70 }
71 MPI_Finalize();
72 return 0;
73 }
74