Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <mpi.h>
- double rand_double() {
- return 2 * (rand() / (double)RAND_MAX) - 1;
- }
- int toss();
- int main()
- {
- srand((long)time(NULL));
- long long int sum = 0;
- double pi_estimate;
- long long int total_number_of_tosses = 0;
- int comm_sz, my_rank, x = 0;
- MPI_Init(NULL, NULL);
- MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
- MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
- if(my_rank == 0){
- fflush( stdout );
- printf("How many tosses will the processes perform : ");
- scanf("%lld", &total_number_of_tosses);
- }
- MPI_Bcast(&total_number_of_tosses, 1, MPI_INT, 0, MPI_COMM_WORLD);
- int k = toss(comm_sz, total_number_of_tosses);
- MPI_Reduce(&k, &sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
- printf("From process with rank %d Hits = %d\n", my_rank, toss(comm_sz, total_number_of_tosses));
- if(my_rank == 0){
- pi_estimate = 4 * sum / ((double)total_number_of_tosses);
- printf("Estimated pi = %f\n", pi_estimate);
- }
- MPI_Finalize();
- return 0;
- }
- int toss(int divide, int tosses){
- int finalNumber = 0;
- double x, y, distance_squared;
- int toss;
- for (toss = 0; toss < tosses / divide ; toss++) {
- x = rand_double();
- y = rand_double();
- distance_squared = x*x + y*y;
- if (distance_squared <= 1){
- ++finalNumber;
- }
- }
- return finalNumber;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement