Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "mpi.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- #include <time.h>
- int main(int argc, char* argv[])
- {
- // Setup
- long num_iterations = atoi(argv[1]);
- long int num_in_circle = 0;
- double sum_pi_approximations = 0;
- int rank, size;
- MPI_Init(&argc, &argv);
- MPI_Comm_rank(MPI_COMM_WORLD, &rank);
- MPI_Comm_size(MPI_COMM_WORLD, &size);
- printf("Hello, world! I am process %d of %d, with id %d\n", rank + 1, size, rank); fflush(stdout);
- MPI_Status mpistatus;
- // An array storing the random seeds for each rank in the cluster
- int *random_seeds = (int*)malloc(sizeof(int*)*size);
- // Worker rank 0 will generate random seeds and send them to other cluster ranks, other cluster ranks receive the random seeds
- srand((unsigned)time(NULL));
- if (rank == 0) {
- for (int i = 0; i < size; i++) {
- random_seeds[i] = rand();
- }
- }
- // Broadcast / receive random seeds
- MPI_Bcast(random_seeds, size, MPI_INT, 0, MPI_COMM_WORLD);
- // Seed local rng with its appropriate value
- printf(" Rank %d local random seed is: %i\n", rank, random_seeds[rank]);
- srand(random_seeds[rank]);
- free(random_seeds);
- // Compute local approximation of PI using dartboard method
- for (int i = 0; i < num_iterations; i++) {
- double r1 = ((double)rand() / (double)RAND_MAX);
- double r2 = ((double)rand() / (double)RAND_MAX);
- if( sqrt( pow(r1-0.5, 2) + pow(r2-0.5, 2) ) <= 0.5 ) {
- //The dart is in the circle, count it
- num_in_circle++;
- }
- }
- // Compute the local pi approximation
- double local_pi_approximation = (float)num_in_circle / (float)num_iterations * 4;
- printf(" Local pie approximation %f\n Num in cicrcle / num iterations %i / %i\n", local_pi_approximation, num_in_circle, num_iterations);
- // Merge the approximations from all ranks
- MPI_Reduce(&local_pi_approximation, &sum_pi_approximations, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
- // Rank 0 outputs results
- if (rank == 0) printf( "Cluster approximation of pie using %i MPI processes: %.53f", size, sum_pi_approximations / size ); fflush(stdout);
- MPI_Finalize();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement