fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <mpi.h>
  4.  
  5. double function(double x) {
  6. return sin(x); // change this to the desired function
  7. }
  8.  
  9. int main(int argc, char *argv[]) {
  10. int i, n, rank, size, local_n;
  11. double a, b, h, x, sum = 0.0, local_sum = 0.0, total_sum = 0.0;
  12.  
  13. MPI_Init(&argc, &argv);
  14. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  15. MPI_Comm_size(MPI_COMM_WORLD, &size);
  16.  
  17. if (rank == 0) {
  18. printf("Enter the lower limit (a): ");
  19. scanf("%lf", &a);
  20. printf("Enter the upper limit (b): ");
  21. scanf("%lf", &b);
  22. printf("Enter the number of intervals (n): ");
  23. scanf("%d", &n);
  24. }
  25.  
  26. MPI_Bcast(&a, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
  27. MPI_Bcast(&b, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
  28. MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
  29.  
  30. h = (b - a) / n;
  31. local_n = n / size;
  32.  
  33. for (i = 0; i < local_n; i++) {
  34. x = a + (rank * local_n + i + 0.5) * h;
  35. local_sum += function(x);
  36. }
  37. local_sum *= h;
  38.  
  39. MPI_Reduce(&local_sum, &total_sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  40.  
  41. if (rank == 0) {
  42. printf("The value of the integral is: %.6f\n", total_sum);
  43. }
  44.  
  45. MPI_Finalize();
  46. return 0;
  47. }
  48.  
Success #stdin #stdout #stderr 0.26s 39024KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected 'function' in "double function"
Execution halted