fork download
  1. #include <stdio.h>
  2. #include <mpi.h>
  3.  
  4. double f(double x) {
  5. return x * x;
  6. }
  7.  
  8. double trapezoidal_rule(double a, double b, int n, double h) {
  9. double integral = (f(a) + f(b)) / 2.0;
  10. for (int i = 1; i < n; i++) {
  11. double x = a + i * h;
  12. integral += f(x);
  13. }
  14. integral *= h;
  15. return integral;
  16. }
  17.  
  18. int main(int argc, char** argv) {
  19. int rank, size, n = 1024;
  20. double a = 0.0, b = 5.0, h, local_a, local_b;
  21. int local_n;
  22. double local_integral, total_integral;
  23.  
  24. MPI_Init(&argc, &argv);
  25. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  26. MPI_Comm_size(MPI_COMM_WORLD, &size);
  27.  
  28. h = (b - a) / n;
  29. local_n = n / size;
  30. local_a = a + rank * local_n * h;
  31. local_b = local_a + local_n * h;
  32.  
  33. // Each process computes its part of the integral
  34. local_integral = trapezoidal_rule(local_a, local_b, local_n, h);
  35.  
  36. // Combine all results into total_integral using MPI_Reduce
  37. MPI_Reduce(&local_integral, &total_integral, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  38.  
  39. // Print the result from rank 0
  40. if (rank == 0) {
  41. printf("The integral of f(x) = x^2 over [0, 5] is: %.6f\n", total_integral);
  42. }
  43.  
  44. MPI_Finalize();
  45. return 0;
  46. }
  47.  
Success #stdin #stdout #stderr 0.27s 40848KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "double f"
Execution halted