--sas

mar18-pi3.c

Mar 24th, 2022 (edited)
524
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <mpi.h>
  4. #include "l17.h"
  5.  
  6. #define CIRCLE(step, i) sqrt(4.0 - (double) (i) * (step) * (double) (i) * (step))
  7.  
  8. int main(int argc, char** argv) {
  9.     int rc;
  10.     rc = MPI_Init(&argc, &argv);
  11.     L17_CHECK_ERROR(MPI_Init, rc);
  12.  
  13.     int size;
  14.     rc = MPI_Comm_size(MPI_COMM_WORLD, &size);
  15.     L17_CHECK_ERROR(MPI_Comm_size, rc);
  16.  
  17.     int rank;
  18.     rc = MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  19.     L17_CHECK_ERROR(MPI_Comm_rank, rc);
  20.  
  21.     int N;
  22.  
  23.     if (rank == 0) {
  24.         FILE* datp = fopen("mar18-pi3.dat", "r");
  25.         if (datp == NULL) {
  26.             printf("Error. Can't open the data file.\n");
  27.             MPI_Abort(MPI_COMM_WORLD, 1);
  28.         }
  29.         rc = fscanf(datp, "%d", &N);
  30.         if (rc != 1) {
  31.             printf("Error. Can't read the N from the data file.\n");
  32.             MPI_Abort(MPI_COMM_WORLD, 2);
  33.         }
  34.         fclose(datp);
  35.     }
  36.  
  37.     rc = MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD);
  38.     L17_CHECK_ERROR(MPI_Bcast, rc);
  39.  
  40.     int ibeg, iend;
  41.     ibeg = (N / size) * rank;
  42.     iend = (rank == size - 1) ? (N - 1) : ((N / size) * (rank + 1) - 1);
  43.     double step = 2.0 / (double) N;
  44.     double f_old = CIRCLE(step, ibeg);
  45.     double f_new;
  46.     double S = 0;
  47.     int i;
  48.     for (i = ibeg; i <= iend; ++i) {
  49.         f_new = CIRCLE(step, i + 1);
  50.         S += (f_old + f_new) * step / 2.0;
  51.         f_old = f_new;
  52.     }
  53.  
  54.     rc = MPI_Reduce((rank == 0) ? MPI_IN_PLACE : &S,
  55.                     &S, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  56.     L17_CHECK_ERROR(MPI_Reduce, rc);
  57.  
  58.     if (rank == 0)
  59.         printf("Pi = %f\n", S);
  60.  
  61.     MPI_Finalize();
  62.  
  63.     return 0;
  64. }
Add Comment
Please, Sign In to add comment