Advertisement
Guest User

Untitled

a guest
Jun 20th, 2018
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 KB | None | 0 0
  1. // This program is to caculate PI using MPI
  2. // The algorithm is based on integral representation of PI. If f(x)=4/(1+x^2), then PI is the intergral of f(x) from 0 to 1
  3.  
  4. #include <stdio.h>
  5. #include <mpi.h>
  6.  
  7. #define N 1E7
  8. #define d 1E-7
  9. #define d2 1E-14
  10.  
  11. int main (int argc, char* argv[])
  12. {
  13.     int rank, size, error, i;
  14.     double pi=0.0, result=0.0, sum=0.0, begin=0.0, end=0.0, x2;
  15.    
  16.     error=MPI_Init (&argc, &argv);
  17.    
  18.     //Get process ID
  19.     MPI_Comm_rank (MPI_COMM_WORLD, &rank);
  20.    
  21.     //Get processes Number
  22.     MPI_Comm_size (MPI_COMM_WORLD, &size);
  23.    
  24.     //Synchronize all processes and get the begin time
  25.     MPI_Barrier(MPI_COMM_WORLD);
  26.     begin = MPI_Wtime();
  27.    
  28.     //Each process will caculate a part of the sum
  29.     for (i=rank; i<N; i+=size)
  30.     {
  31.         x2=d2*i*i;
  32.         result+=1.0/(1.0+x2);
  33.     }
  34.    
  35.     //Sum up all results
  36.     MPI_Reduce(&result, &sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  37.    
  38.     //Synchronize all processes and get the end time
  39.     MPI_Barrier(MPI_COMM_WORLD);
  40.     end = MPI_Wtime();
  41.    
  42.     //Caculate and print PI
  43.     if (rank==0)
  44.     {
  45.         pi=4*d*sum;
  46.         printf("np=%2d;    Time=%fs;    PI=%lf\n", size, end-begin, pi);
  47.     }
  48.    
  49.     error=MPI_Finalize();
  50.    
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement