Advertisement
--sas

apr22-pi1.c

Apr 28th, 2022
1,946
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.22 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <stdlib.h>
  4. #include <omp.h>
  5.  
  6. #define CIRCLE(step, i) sqrt(4.0 - (double) (i) * (step) * (double) (i) * (step))
  7.  
  8. int main() {
  9.     omp_set_num_threads(omp_get_num_procs());
  10.  
  11.     int N;
  12.     FILE* datp = fopen("apr22-pi1.dat", "r");
  13.     if (datp == NULL) {
  14.         printf("Error. Couldn't open the data file.");
  15.         exit(1);
  16.     }
  17.     if (fscanf(datp, "%d", &N) != 1) {
  18.         printf("Error. Couldn't read the number from the data file.");
  19.         exit(2);
  20.     }
  21.     fclose(datp);
  22.    
  23.     int i, ibeg, iend, size, rank;
  24.     double step = 2.0 / (double) N;
  25.     double f_old, f_new, S = 0.0;
  26.  
  27. #pragma omp parallel shared(step, size, N) private(i, ibeg, iend, rank, f_old, f_new) reduction(+:S)
  28.     {
  29.         size = omp_get_num_threads();
  30.         rank = omp_get_thread_num();
  31.         ibeg = (N / size) * rank;
  32.         iend = (rank == size - 1) ? (N - 1) : ((N / size) * (rank + 1) - 1);
  33.         f_old = CIRCLE(step, ibeg);
  34.         S = 0.0;
  35.  
  36.         for (i = ibeg; i <= iend; ++i) {
  37.             f_new = CIRCLE(step, i + 1);
  38.             S += (f_old + f_new) * step / 2.0;
  39.             f_old = f_new;
  40.         }
  41.     }
  42.  
  43.     printf("Pi = %f\n", S);
  44.  
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement