/***************************************************************************/ /* ____Demonstrates SPRNG use for Monte Carlo integration____ */ /* Compute pi using Monte Carlo integration. Random points are generated */ /* in a square of size 2. The value of pi is estimated as four times the */ /* the proportion of samples that fall within a circle of unit radius. */ /* The final state of the computations is check-pointed at the end, so the */ /* the calculations can be continued from the previous state. However, the */ /* same number of processors should be used as in the previous run. */ /***************************************************************************/ #include #include #include #include "mpi.h" #define SIMPLE_SPRNG /* simple interface */ #define USE_MPI /* MPI version of SPRNG */ #include "sprng.h" #define EXACT_PI 3.141592653589793238462643 #define RECV_STREAM_TAG 1 int gtype; /*--- */ main(argc,argv) int argc; char *argv[]; { int in, i, seed, n, my_n, in_old, n_old, nprocs, myid, temp; double pi, error, stderror, p=EXACT_PI/4.0; char filename[80]; /*************************** Initialization ******************************/ MPI_Init(&argc,&argv); /* Initialize MPI */ MPI_Comm_size(MPI_COMM_WORLD,&nprocs); /* Find number of processes */ MPI_Comm_rank(MPI_COMM_WORLD,&myid); /* Find rank of process */ /*--- node 0 is reading in a generator type */ if(myid == 0) { /* You may not need this. This is for generator type explanation. *******/ #include "gen_types_menu.h" printf("Type in an integer for the generator type: "); scanf("%d", >ype); } MPI_Bcast(>ype,1,MPI_INT,0,MPI_COMM_WORLD ); /**************** read args & initialize *********************************/ initialize_function(&n, &in_old, &n_old, filename); my_n = n/nprocs; /* number of samples for this process */ if(myid < n%nprocs) my_n++; /******************** Count number of samples in circle ******************/ temp = count_in_circle(my_n); /* count samples in circle */ /* sum # in circle over all processes */ MPI_Reduce(&temp, &in, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); /*************************** Determine Pi ********************************/ if(myid == 0) { in += in_old; /* # in circle, in all runs */ n += n_old; /* # of samples, in all runs */ pi = (4.0*in)/n; /* estimate pi */ error = fabs(pi - EXACT_PI); /* determine error */ stderror = 4*sqrt(p*(1.0-p)/n); /* standard error */ printf( "pi is estimated as %18.16f from %12d samples.\n", pi, n); printf( "\tError = %10.8g, standard error = %10.8g\n", error, stderror); } /*************************** Save final state ****************************/ save_state(filename,in,n); /* save final state of computation*/ MPI_Finalize(); /* Terminate MPI */ } int count_in_circle(n) /* count # of samples in circle */ int n; { int i, in; double x, y; for (i=in=0; i