fork download
  1. #include <iostream>
  2. #include <cmath>
  3. #include <mpi.h>
  4. #include <vector>
  5.  
  6. // Function to compute the value of the function f(x)
  7. double f(double x) {
  8. return log(x) - (1.0 / 8.0) * x * x;
  9. }
  10.  
  11. // Function to compute the derivative f'(x)
  12. double f_prime(double x) {
  13. return 1.0 / x - (1.0 / 4.0) * x;
  14. }
  15.  
  16. // Function to compute the integrand sqrt(1 + (f'(x))^2)
  17. double integrand(double x) {
  18. double fp = f_prime(x);
  19. return sqrt(1 + fp * fp);
  20. }
  21.  
  22. // Function to perform the Riemann sum in parallel using MPI
  23. double riemann_sum(double a, double b, int n, int rank, int size) {
  24. double h = (b - a) / n;
  25. double local_sum = 0.0;
  26.  
  27. for (int i = rank; i < n; i += size) {
  28. double x_i = a + i * h;
  29. local_sum += integrand(x_i);
  30. }
  31.  
  32. double global_sum = 0.0;
  33. MPI_Reduce(&local_sum, &global_sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  34.  
  35. return global_sum * h;
  36. }
  37.  
  38. int main(int argc, char *argv[]) {
  39. MPI_Init(&argc, &argv);
  40.  
  41. int rank, size;
  42. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  43. MPI_Comm_size(MPI_COMM_WORLD, &size);
  44.  
  45. double a = 1.0;
  46. double b = 6.0;
  47. int n = 100000000; // 1.e8 partition points
  48. if (argc > 1) {
  49. n = std::stoi(argv[1]);
  50. }
  51.  
  52. double start_time = MPI_Wtime();
  53. double length = riemann_sum(a, b, n, rank, size);
  54. double end_time = MPI_Wtime();
  55.  
  56. if (rank == 0) {
  57. std::cout << "Length of the curve: " << length << std::endl;
  58. std::cout << "Time taken: " << end_time - start_time << " seconds" << std::endl;
  59. }
  60.  
  61. MPI_Finalize();
  62. return 0;
  63. }
  64.  
Success #stdin #stdout #stderr 0.26s 40868KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected '/' in "/"
Execution halted