proffreda

mpi_pi.c

Nov 8th, 2016
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. /* MPI program that uses a monte carlo method to compute the value of PI */
  2.  
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <math.h>
  6. #include <string.h>
  7. #include <stdio.h>
  8. #include <sprng.h>
  9. #include <mpi.h>
  10. #define USE_MPI
  11. #define SEED 35791246
  12.  
  13. main(int argc, char *argv[])
  14. {
  15. int niter=0;
  16. double x,y;
  17. int i,j,count=0,mycount; /* # of points in the 1st quadrant of unit circle */
  18. double z;
  19. double pi;
  20. int myid,numprocs,proc;
  21. MPI_Status status;
  22. int master =0;
  23. int tag = 123;
  24. int *stream_id; /* stream id generated by SPRNGS */
  25.  
  26. MPI_Init(&argc,&argv);
  27. MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
  28. MPI_Comm_rank(MPI_COMM_WORLD,&myid);
  29.  
  30. if (argc <=1) {
  31. fprintf(stderr,"Usage: monte_pi_mpi number_of_iterations\n");
  32. MPI_Finalize();
  33. exit(-1);
  34. }
  35.  
  36. sscanf(argv[1],"%d",&niter); /* 1st argument is the number of iterations*/
  37.  
  38. /* initialize random numbers */
  39. stream_id = init_sprng(myid,numprocs,SEED,SPRNG_DEFAULT);
  40. mycount=0;
  41. for ( i=0; i<niter; i++) {
  42. x = (double)sprng(stream_id);
  43. y = (double)sprng(stream_id);
  44. z = x*x+y*y;
  45. if (z<=1) mycount++;
  46. }
  47. if (myid ==0) { /* if I am the master process gather results from others */
  48. count = mycount;
  49. for (proc=1; proc<numprocs; proc++) {
  50. MPI_Recv(&mycount,1,MPI_REAL,proc,tag,MPI_COMM_WORLD,&status);
  51. count +=mycount;
  52. }
  53. pi=(double)count/(niter*numprocs)*4;
  54. printf("\n # of trials= %d , estimate of pi is %g \n",niter*numprocs,pi);
  55. }
  56. else { /* for all the slave processes send results to the master */
  57. printf("Processor %d sending results= %d to master process\n",myid,mycount
  58. );
  59. MPI_Send(&mycount,1,MPI_REAL,master,tag,MPI_COMM_WORLD);
  60. }
Advertisement
Add Comment
Please, Sign In to add comment