Advertisement
Guest User

Untitled

a guest
Dec 15th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <mpi.h>
  5. double rand_double() {
  6.  
  7. return 2 * (rand() / (double)RAND_MAX) - 1;
  8. }
  9. int toss();
  10. int main()
  11. {
  12. srand((long)time(NULL));
  13. long long int sum = 0;
  14. double pi_estimate;
  15. long long int total_number_of_tosses = 0;
  16. int comm_sz, my_rank, x = 0;
  17. MPI_Init(NULL, NULL);
  18. MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
  19. MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
  20. if(my_rank == 0){
  21. fflush( stdout );
  22. printf("How many tosses will the processes perform : ");
  23. scanf("%lld", &total_number_of_tosses);
  24. }
  25. MPI_Bcast(&total_number_of_tosses, 1, MPI_INT, 0, MPI_COMM_WORLD);
  26. int k = toss(comm_sz, total_number_of_tosses);
  27. MPI_Reduce(&k, &sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
  28. printf("From process with rank %d Hits = %d\n", my_rank, toss(comm_sz, total_number_of_tosses));
  29. if(my_rank == 0){
  30. pi_estimate = 4 * sum / ((double)total_number_of_tosses);
  31. printf("Estimated pi = %f\n", pi_estimate);
  32. }
  33. MPI_Finalize();
  34. return 0;
  35.  
  36.  
  37. }
  38.  
  39. int toss(int divide, int tosses){
  40. int finalNumber = 0;
  41. double x, y, distance_squared;
  42. int toss;
  43. for (toss = 0; toss < tosses / divide ; toss++) {
  44.  
  45. x = rand_double();
  46. y = rand_double();
  47. distance_squared = x*x + y*y;
  48. if (distance_squared <= 1){
  49. ++finalNumber;
  50. }
  51. }
  52. return finalNumber;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement