#include <stdio.h>
#include <mpi.h>
#define N 5040
#define a 0.0
#define b 8.0
double function(double x) {
return 3 * x * x * x + 2 * x * x - 7 * x;
}
double trapezoidal(double local_a, double local_b, int local_n, double h) {
double integral = (function(local_a) + function(local_b)) / 2.0;
for (int i = 1; i < local_n; i++) {
double x_i = local_a + i * h;
integral += function(x_i);
}
return integral * h;
}
int main(int argc, char** argv) {
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
int local_n = N / size;
double h = (b - a) / N;
double local_a = a + rank * local_n * h;
double local_b = local_a + local_n * h;
double local_integral = trapezoidal(local_a, local_b, local_n, h);
double total_integral;
MPI_Reduce(&local_integral, &total_integral, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if (rank == 0) {
printf("The total area under the curve is: %lf\n", total_integral
); }
MPI_Finalize();
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxtcGkuaD4KCiNkZWZpbmUgTiA1MDQwCiNkZWZpbmUgYSAwLjAKI2RlZmluZSBiIDguMAoKZG91YmxlIGZ1bmN0aW9uKGRvdWJsZSB4KSB7CiAgICByZXR1cm4gMyAqIHggKiB4ICogeCArIDIgKiB4ICogeCAtIDcgKiB4Owp9Cgpkb3VibGUgdHJhcGV6b2lkYWwoZG91YmxlIGxvY2FsX2EsIGRvdWJsZSBsb2NhbF9iLCBpbnQgbG9jYWxfbiwgZG91YmxlIGgpIHsKICAgIGRvdWJsZSBpbnRlZ3JhbCA9IChmdW5jdGlvbihsb2NhbF9hKSArIGZ1bmN0aW9uKGxvY2FsX2IpKSAvIDIuMDsKICAgIGZvciAoaW50IGkgPSAxOyBpIDwgbG9jYWxfbjsgaSsrKSB7CiAgICAgICAgZG91YmxlIHhfaSA9IGxvY2FsX2EgKyBpICogaDsKICAgICAgICBpbnRlZ3JhbCArPSBmdW5jdGlvbih4X2kpOwogICAgfQogICAg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