#include <stdio.h>
#include <mpi.h>
double f(double x) {
return x * x;
}
double trapezoidal_rule(double a, double b, int n, double h) {
double integral = (f(a) + f(b)) / 2.0;
for (int i = 1; i < n; i++) {
double x = a + i * h;
integral += f(x);
}
integral *= h;
return integral;
}
int main(int argc, char** argv) {
int rank, size, n = 1024;
double a = 0.0, b = 5.0, h, local_a, local_b;
int local_n;
double local_integral, total_integral;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
h = (b - a) / n;
local_n = n / size;
local_a = a + rank * local_n * h;
local_b = local_a + local_n * h;
// Each process computes its part of the integral
local_integral = trapezoidal_rule(local_a, local_b, local_n, h);
// Combine all results into total_integral using MPI_Reduce
MPI_Reduce(&local_integral, &total_integral, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
// Print the result from rank 0
if (rank == 0) {
printf("The integral of f(x) = x^2 over [0, 5] is: %.6f\n", total_integral
); }
MPI_Finalize();
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxtcGkuaD4KCmRvdWJsZSBmKGRvdWJsZSB4KSB7CiAgICByZXR1cm4geCAqIHg7Cn0KCmRvdWJsZSB0cmFwZXpvaWRhbF9ydWxlKGRvdWJsZSBhLCBkb3VibGUgYiwgaW50IG4sIGRvdWJsZSBoKSB7CiAgICBkb3VibGUgaW50ZWdyYWwgPSAoZihhKSArIGYoYikpIC8gMi4wOwogICAgZm9yIChpbnQgaSA9IDE7IGkgPCBuOyBpKyspIHsKICAgICAgICBkb3VibGUgeCA9IGEgKyBpICogaDsKICAgICAgICBpbnRlZ3JhbCArPSBmKHgpOwogICAgfQogICAgaW50ZWdyYWwgKj0gaDsKICAgIHJldHVybiBpbnRlZ3JhbDsKfQoKaW50IG1haW4oaW50IGFyZ2MsIGNoYXIqKiBhcmd2KSB7CiAgICBpbnQgcmFuaywgc2l6ZSwgbiA9IDEwMjQ7CiAgICBk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