#include <iostream>
#include <cmath>
#include <mpi.h>
#include <vector>
// Function to compute the value of the function f(x)
double f(double x) {
return log(x
) - (1.0 / 8.0) * x
* x
; }
// Function to compute the derivative f'(x)
double f_prime(double x) {
return 1.0 / x - (1.0 / 4.0) * x;
}
// Function to compute the integrand sqrt(1 + (f'(x))^2)
double integrand(double x) {
double fp = f_prime(x);
return sqrt(1 + fp
* fp
); }
// Function to perform the Riemann sum in parallel using MPI
double riemann_sum(double a, double b, int n, int rank, int size) {
double h = (b - a) / n;
double local_sum = 0.0;
for (int i = rank; i < n; i += size) {
double x_i = a + i * h;
local_sum += integrand(x_i);
}
double global_sum = 0.0;
MPI_Reduce(&local_sum, &global_sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
return global_sum * h;
}
int main(int argc, char *argv[]) {
MPI_Init(&argc, &argv);
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
double a = 1.0;
double b = 6.0;
int n = 100000000; // 1.e8 partition points
if (argc > 1) {
n = std::stoi(argv[1]);
}
double start_time = MPI_Wtime();
double length = riemann_sum(a, b, n, rank, size);
double end_time = MPI_Wtime();
if (rank == 0) {
std::cout << "Length of the curve: " << length << std::endl;
std::cout << "Time taken: " << end_time - start_time << " seconds" << std::endl;
}
MPI_Finalize();
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y21hdGg+CiNpbmNsdWRlIDxtcGkuaD4KI2luY2x1ZGUgPHZlY3Rvcj4KCi8vIEZ1bmN0aW9uIHRvIGNvbXB1dGUgdGhlIHZhbHVlIG9mIHRoZSBmdW5jdGlvbiBmKHgpCmRvdWJsZSBmKGRvdWJsZSB4KSB7CiAgICByZXR1cm4gbG9nKHgpIC0gKDEuMCAvIDguMCkgKiB4ICogeDsKfQoKLy8gRnVuY3Rpb24gdG8gY29tcHV0ZSB0aGUgZGVyaXZhdGl2ZSBmJyh4KQpkb3VibGUg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