Guest User

Untitled

a guest
May 27th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. #define A 1.0 // Integral starting position
  2. #define B 2.0 // Integral ending position
  3. #define W .001 // Integral step size
  4.  
  5. #include <stdio.h>
  6. #include <mpi.h>
  7. #define round(v) (float)(int)(v / W) * W
  8.  
  9. double f(double x) {
  10. return x * x + 5 * x + 3;
  11. }
  12.  
  13. int main(int argc, char* argv[]) {
  14. int i;
  15. int id, p;
  16. MPI_Init(&argc, &argv);
  17. MPI_Comm_size(MPI_COMM_WORLD, &p);
  18. MPI_Comm_rank(MPI_COMM_WORLD, &id);
  19.  
  20. // Calculates job boundaries and prints them in order
  21. double a, b, da, db, wpp;
  22. wpp = (B - A) / p;
  23. da = wpp * id;
  24. db = wpp * (id + 1);
  25. a = A + round(da);
  26. b = A + round(db);
  27. for (i = 0; i < p; i++) {
  28. if (i == id) printf("Process #%d: f(%f) to f(%f)\n", id, a, b);
  29. MPI_Barrier(MPI_COMM_WORLD);
  30. }
  31.  
  32. // Processes job
  33. double sum = 0, x;
  34. for (x = a; x < b; x += W)
  35. sum += f(x) * W;
  36.  
  37. // Reduces result and displays
  38. double grand_sum = 0;
  39. MPI_Reduce(&sum, &grand_sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  40. if (id == 0) printf("Result of integral: %f\n", grand_sum);
  41.  
  42. MPI_Finalize();
  43. }
Add Comment
Please, Sign In to add comment