Advertisement
catbert

pi

Sep 21st, 2015
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 KB | None | 0 0
  1. /* a MC example calculate value of pi*/
  2.  
  3. //const double totaltry=10000;
  4.  
  5. #include <stdlib.h>
  6. #include <iostream>
  7. #include <string>
  8. #include <mpi.h>
  9.  
  10. using namespace std;
  11.  
  12. int main(int argc, char** argv) {
  13.  
  14.   double totaltry(10000);
  15.  
  16.   if (argc != 2) {
  17.     cout << "Usage: \n" << argv[0] << " <# of trys>\n";
  18.     return(1);
  19.   }
  20.  
  21.   totaltry = stof(argv[1], 0);
  22.   // Initialize the MPI environment
  23.   MPI_Status mpistat;
  24.   double HITSBUF[1];
  25.   double starttime, endtime;
  26.  
  27.   MPI_Init(0, 0);
  28.  
  29.   // Get the number of processes
  30.   int world_size;
  31.   MPI_Comm_size(MPI_COMM_WORLD, &world_size);
  32.   // Get the rank of the process
  33.   int world_rank;
  34.   MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
  35.  
  36.   srand(time(0)+world_rank);
  37.  
  38.   for (int num_nodes = 1; num_nodes <= world_size; num_nodes <<= 1) {
  39.  
  40.     starttime = MPI_Wtime();
  41.     MPI_Barrier(MPI_COMM_WORLD);
  42.     double eachtry = totaltry/num_nodes;
  43.     double localhits=0;
  44.     double lbound = (eachtry * world_rank)/totaltry;
  45.     double vy, vx;
  46.     for (int i=0; i< eachtry ; i++) {
  47.       vy = rand()*1.0/RAND_MAX;
  48.       vx = lbound+i/totaltry;
  49.       localhits += (vx*vx + vy*vy) < 1;
  50.     }
  51.     MPI_Barrier(MPI_COMM_WORLD);
  52.  
  53.     int mask = 0xFFFFFFFE;
  54.     for (int level=num_nodes; level>1; level/=2) {
  55.       int sourcenode = world_rank & mask;
  56.       int targetnode = world_rank | (~mask);
  57.       if (world_rank == sourcenode) {
  58.         *HITSBUF = localhits;
  59.         MPI_Send(HITSBUF, 1, MPI_DOUBLE, targetnode, 1, MPI_COMM_WORLD);
  60.       } else {
  61.         MPI_Recv(HITSBUF, 1, MPI_DOUBLE, sourcenode, 1, MPI_COMM_WORLD, &mpistat
  62. );
  63.         localhits += *HITSBUF;
  64.       }
  65.       mask = mask << 1 | 1;
  66.     }
  67.     endtime = MPI_Wtime();
  68.  
  69.     if (world_rank == num_nodes - 1)
  70.       cout << " pi: "<< localhits*4.0/totaltry
  71.         << " number of nodes: " << num_nodes
  72.         << " taking " << endtime-starttime << " seconds" << endl;
  73.   }
  74.  
  75.   // Finalize the MPI environment.
  76.   MPI_Finalize();
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement