fork download
  1. #include <stdio.h>
  2. #include <mpi.h>
  3.  
  4. #define N 5040
  5. #define a 0.0
  6. #define b 8.0
  7.  
  8. double function(double x) {
  9. return 3 * x * x * x + 2 * x * x - 7 * x;
  10. }
  11.  
  12. double trapezoidal(double local_a, double local_b, int local_n, double h) {
  13. double integral = (function(local_a) + function(local_b)) / 2.0;
  14. for (int i = 1; i < local_n; i++) {
  15. double x_i = local_a + i * h;
  16. integral += function(x_i);
  17. }
  18. return integral * h;
  19. }
  20.  
  21. int main(int argc, char** argv) {
  22. int rank, size;
  23. MPI_Init(&argc, &argv);
  24. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  25. MPI_Comm_size(MPI_COMM_WORLD, &size);
  26.  
  27. int local_n = N / size;
  28. double h = (b - a) / N;
  29. double local_a = a + rank * local_n * h;
  30. double local_b = local_a + local_n * h;
  31.  
  32. double local_integral = trapezoidal(local_a, local_b, local_n, h);
  33.  
  34. double total_integral;
  35. MPI_Reduce(&local_integral, &total_integral, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  36.  
  37. if (rank == 0) {
  38. printf("The total area under the curve is: %lf\n", total_integral);
  39. }
  40.  
  41. MPI_Finalize();
  42. return 0;
  43. }
  44.  
Success #stdin #stdout #stderr 0.29s 40768KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected 'function' in "double function"
Execution halted