fork download
  1. #include <mpi.h>
  2. #include <math.h> // Add this line
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5.  
  6. int main(int argc, char *argv[]) {
  7. int myid, numprocs, i;
  8. unsigned long n;
  9. long double PI = 3.14159265358979323846264338327950288419716939937510;
  10. long double pi, sum, partial_sum, x;
  11.  
  12. MPI_Init(&argc, &argv);
  13. MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
  14. MPI_Comm_rank(MPI_COMM_WORLD, &myid);
  15.  
  16. if (myid == 0) {
  17. if (argc != 2) {
  18. printf("Usage: %s <num_terms>\n", argv[0]);
  19. MPI_Abort(MPI_COMM_WORLD, 1);
  20. }
  21. n = strtoul(argv[1], NULL, 10);
  22. }
  23.  
  24. MPI_Bcast(&n, 1, MPI_UNSIGNED_LONG, 0, MPI_COMM_WORLD);
  25.  
  26. partial_sum = 0.0;
  27. for(i = n / numprocs * myid + 1; i <= n / numprocs * (myid + 1); i++) {
  28. x = ((long double)i - 0.5) / n;
  29. partial_sum += 4.0 / (1.0 + x * x);
  30. }
  31.  
  32. MPI_Reduce(&partial_sum, &sum, 1, MPI_LONG_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  33.  
  34. if (myid == 0) {
  35. pi = sum / n;
  36. printf("pi is approximately %.22Lf, Error is %.22Lf\n", pi, fabsl(pi - PI));
  37. }
  38.  
  39. MPI_Finalize();
  40. return 0;
  41. }
  42.  
Success #stdin #stdout #stderr 0.27s 40688KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "int main"
Execution halted