Cawa245

Untitled

Dec 15th, 2020
482
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <cstdio>
  2. #include "mpi.h"
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7. float integral(const float a, const int n, const float h)
  8. {
  9.     float result = 0.0;
  10.     const float local_h = h / 2.0;
  11.     for (auto i = 0; i < n; i++)
  12.     {
  13.         const auto aij = a + i * h;
  14.         result += (aij + local_h) * (aij + local_h) * h;
  15.     }
  16.     return result;
  17. }
  18.  
  19. void main(int argc, char* argv[])
  20. {
  21.     int p,id;
  22.     MPI_Status status;
  23.     float result;
  24.  
  25.     const float a = 1;
  26.     const float b = 4;
  27.     const auto n = 100000;
  28.  
  29.     const auto dest = 0;
  30.     const auto tag = 0;
  31.    
  32.  
  33.     MPI_Init(&argc, &argv);
  34.     MPI_Comm_rank(MPI_COMM_WORLD, &id);
  35.     MPI_Comm_size(MPI_COMM_WORLD, &p);
  36.  
  37.     const auto h = (b - a) / n;
  38.     const auto num = n / p;
  39.     const auto range = (b - a) / p;
  40.     const auto x = a + id * range;
  41.     result = integral(x, num, h);
  42.  
  43.     printf("Rank %d, sum = %f\n", id, result);
  44.  
  45.     if (id == 0)
  46.     {
  47.         auto loacl_result = result;
  48.         for (auto i = 1; i < p; i++)
  49.         {
  50.             const auto source = i;
  51.             MPI_Recv(&result, 1, MPI_REAL, source, tag,
  52.                      MPI_COMM_WORLD, &status);
  53.             loacl_result += result;
  54.         }
  55.         printf("Total sum = %f\n", loacl_result);
  56.     }
  57.     else
  58.         MPI_Send(&result, 1, MPI_REAL, dest, tag,
  59.                  MPI_COMM_WORLD);
  60.  
  61.     MPI_Finalize();
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment