rjcostales

calc_pi.c

Jan 29th, 2022 (edited)
391
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.69 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include "mpi.h"
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7.     int cpu, num;
  8.     unsigned int i, n;
  9.     double sub, pi, x, dx, sum;
  10.     double PI25DT = 3.141592653589793238462643;
  11.  
  12.     MPI_Init(&argc, &argv);
  13.     MPI_Comm_size(MPI_COMM_WORLD, &num);
  14.     MPI_Comm_rank(MPI_COMM_WORLD, &cpu);
  15.  
  16.     n = 4000000000;
  17.  
  18.     dx  = 1.0 / (double) n;
  19.     sum = 0.0;
  20.     for (i = cpu; i < n; i += num) {
  21.         x = dx * ((double)i - 0.5);
  22.         sum += (4.0 / (1.0 + x*x));
  23.     }
  24.     sub = dx * sum;
  25.  
  26.     MPI_Reduce(&sub, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  27.  
  28.     if (cpu == 0)
  29.         printf("pi is approximately %.15f, Error is %.12f\n",
  30.                   pi, fabs(pi - PI25DT));
  31.  
  32.     MPI_Finalize();
  33.     return 0;
  34. }
  35.  
Add Comment
Please, Sign In to add comment