Advertisement
davidparks21

AMS250

May 10th, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. #include "mpi.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <math.h>
  5. #include <time.h>
  6.  
  7. int main(int argc, char* argv[])
  8. {
  9.     // Setup
  10.     long num_iterations = atoi(argv[1]);
  11.     long int num_in_circle = 0;
  12.     double sum_pi_approximations = 0;
  13.     int rank, size;
  14.     MPI_Init(&argc, &argv);
  15.     MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  16.     MPI_Comm_size(MPI_COMM_WORLD, &size);
  17.     printf("Hello, world! I am process %d of %d, with id %d\n", rank + 1, size, rank); fflush(stdout);
  18.     MPI_Status mpistatus;
  19.  
  20.     // An array storing the random seeds for each rank in the cluster
  21.     int *random_seeds = (int*)malloc(sizeof(int*)*size);
  22.  
  23.     // Worker rank 0 will generate random seeds and send them to other cluster ranks, other cluster ranks receive the random seeds
  24.     srand((unsigned)time(NULL));
  25.     if (rank == 0) {
  26.         for (int i = 0; i < size; i++) {
  27.             random_seeds[i] = rand();
  28.         }
  29.     }
  30.  
  31.     // Broadcast / receive random seeds
  32.     MPI_Bcast(random_seeds, size, MPI_INT, 0, MPI_COMM_WORLD);
  33.    
  34.     // Seed local rng with its appropriate value
  35.     printf(" Rank %d local random seed is: %i\n", rank, random_seeds[rank]);
  36.     srand(random_seeds[rank]);
  37.     free(random_seeds);
  38.  
  39.     // Compute local approximation of PI using dartboard method
  40.     for (int i = 0; i < num_iterations; i++) {
  41.         double r1 = ((double)rand() / (double)RAND_MAX);
  42.         double r2 = ((double)rand() / (double)RAND_MAX);
  43.         if( sqrt( pow(r1-0.5, 2) + pow(r2-0.5, 2) ) <= 0.5 ) {
  44.             //The dart is in the circle, count it
  45.             num_in_circle++;
  46.         }
  47.     }
  48.  
  49.     // Compute the local pi approximation
  50.     double local_pi_approximation = (float)num_in_circle / (float)num_iterations * 4;
  51.     printf(" Local pie approximation %f\n Num in cicrcle / num iterations %i / %i\n", local_pi_approximation, num_in_circle, num_iterations);
  52.    
  53.     // Merge the approximations from all ranks
  54.     MPI_Reduce(&local_pi_approximation, &sum_pi_approximations, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  55.  
  56.     // Rank 0 outputs results
  57.     if (rank == 0) printf( "Cluster approximation of pie using %i MPI processes: %.53f", size, sum_pi_approximations / size ); fflush(stdout);
  58.  
  59.     MPI_Finalize();
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement