fork download
  1. #include <iostream>
  2. #include "mpi.h"
  3. using namespace std;
  4. //compute the trapzoidal area for the function x*x from 0 to 1 with 1024 trapzoid
  5. float f(float x)
  6. {
  7. return x * x;
  8. }
  9. float Trap(float a, float b, int n, float h)
  10. {
  11. float integral, x;
  12. int i;
  13. integral = (f(a) + f(b)) / 2.0;
  14. x = a;
  15. for (i = 1; i <= n - 1; i++)
  16. {
  17. x = x + h;
  18. integral = integral + f(x);
  19. }
  20. return integral * h;
  21. }
  22. int main(int argc, char** argv)
  23. {
  24. int my_rank, p;
  25. float a = 0.0;
  26. float b = 1.0;
  27. int n = 1024;
  28. float h, local_a, local_b;
  29. int local_n;
  30. float integral;
  31. float total = -1;
  32. int source;
  33. int dest = 0;
  34. int tage = 0;
  35. MPI_Status status;
  36. MPI_Init(&argc, &argv);
  37. MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
  38. MPI_Comm_size(MPI_COMM_WORLD, &p);
  39. h = (b - a) / n;
  40. local_n = n / p;
  41. local_a = a + my_rank * local_n * h;
  42. local_b = local_a + local_n * h;
  43. integral = Trap(local_a, local_b, local_n, h);
  44. if (my_rank == 0)
  45. {
  46. total = integral;
  47. for (source = 1; source < p; source++)
  48. {
  49. MPI_Recv(&integral, 1, MPI_FLOAT, source, tage, MPI_COMM_WORLD,
  50. &status);
  51. cout << "PE " << my_rank << " is " << source << " " << integral << "\n";
  52. total = total + integral;
  53. }
  54. }
  55. else
  56. {
  57. cout << "PE " << my_rank << " is " << dest << " " << integral << "\n";
  58. MPI_Send(&integral, 1, MPI_FLOAT, dest, tage, MPI_COMM_WORLD);
  59. }
  60. if (my_rank == 0)
  61. {
  62. cout << "with n == "<<n<<" trapezoids, \n Our estimate";
  63. cout << " of the integral from " << a << " to " << b << "= "<<total<<"\n";
  64. }
  65. MPI_Finalize();
  66. return 0;
  67. }
Success #stdin #stdout #stderr 0.27s 40600KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "using namespace"
Execution halted