#include <iostream>
#include <mpi.h>
#include <cmath>
using namespace std;
// Функция для вычисления интеграла методом прямоугольников
double rectangular_method(double a, double b, int n, double (*func)(double)) {
double h = (b - a) / n;
double sum = 0.0;
for (int i = 0; i < n; ++i) {
double x = a + i * h;
sum += func(x);
}
return sum * h;
}
// Функция для вычисления интеграла методом Симпсона
double simpson_method(double a, double b, int n, double (*func)(double)) {
double h = (b - a) / n;
double sum = func(a) + func(b);
for (int i = 1; i < n; i += 2) {
double x = a + i * h;
sum += 4 * func(x);
}
for (int i = 2; i < n - 1; i += 2) {
double x = a + i * h;
sum += 2 * func(x);
}
return sum * h / 3;
}
// Функция для интегрирования
double example_function(double x) {
return x
/ sqrt(x
- x
* x
); }
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 / 2.0;
double b = 3.0 / 4.0;
int n = 100000; // Количество разбиений
double local_a = a + rank * (b - a) / size;
double local_b = a + (rank + 1) * (b - a) / size;
double local_rectangular_result = rectangular_method(local_a, local_b, n / size, example_function);
double local_simpson_result = simpson_method(local_a, local_b, n / size, example_function);
double global_rectangular_result = 0.0;
double global_simpson_result = 0.0;
MPI_Reduce(&local_rectangular_result, &global_rectangular_result, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&local_simpson_result, &global_simpson_result, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if (rank == 0) {
cout << "Rectangular Method Result: " << global_rectangular_result << endl;
cout << "Simpson Method Result: " << global_simpson_result << endl;
}
MPI_Finalize();
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8bXBpLmg+CiNpbmNsdWRlIDxjbWF0aD4KCnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgovLyDQpNGD0L3QutGG0LjRjyDQtNC70Y8g0LLRi9GH0LjRgdC70LXQvd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