fork download
  1. #include <stdio.h>
  2. #include <mpi.h>
  3. #include <math.h>
  4.  
  5. #define PI 3.14159265358979323846
  6. #define INTERVALS 1000000
  7.  
  8. // Function to compute y-coordinate of the pi curve
  9. double compute_pi(double x) {
  10. return 4.0 / (1.0 + x * x);
  11. }
  12.  
  13. int main(int argc, char** argv) {
  14. int rank, size;
  15. double area = 0.0;
  16. double width = 1.0 / INTERVALS;
  17. double x;
  18.  
  19. // Initialize MPI
  20. MPI_Init(&argc, &argv);
  21. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  22. MPI_Comm_size(MPI_COMM_WORLD, &size);
  23.  
  24. // Each process calculates its portion of the area
  25. for (int i = rank; i < INTERVALS; i += size) {
  26. x = (i + 0.5) * width;
  27. area += compute_pi(x);
  28. }
  29.  
  30. double total_area;
  31. // Reduce the partial areas from all processes to get the total area
  32. MPI_Reduce(&area, &total_area, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  33.  
  34. // Only process 0 prints the result
  35. if (rank == 0) {
  36. double pi = total_area * width;
  37. printf("Approximation of Pi: %.16f\n", pi);
  38. }
  39.  
  40. // Finalize MPI
  41. MPI_Finalize();
  42. return 0;
  43. }
  44.  
Success #stdin #stdout #stderr 0.3s 40416KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected '/' in "/"
Execution halted