#include<stdio.h>
#include<math.h>
#include "mpi.h"
double f(double x)
{
if(!x)
return exp(x)*1.0 / pow(x, 2)*sin(1.0 / x);
}
double trap(double local_a, double local_b, int local_n, double h)
{
double res = (f(local_a) + f(local_b)) / 2.0;
for (int i = 1; i <= local_n - 1;i++)
{
double xi = local_a + h*i;
res += f(xi);
}
res = h*res;
return res;
}
int main(int argc, char* argv[])
{
double a = 1.0*pow(10, -9);
double b = 10;
long long n = pow(10, 8);
double h = (b - a)*1.0 / n;
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
long long local_n = n / size;
double local_a = a + rank*local_n*h;
double local_b = local_a + local_n*h;
double local_integral = trap(local_a, local_b, local_n, h);
double total_integral;
double start, end;
start = MPI_Wtime();
if (rank != 0)
{
MPI_Send(&local_integral, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
printf("The %dth pthread has sent an integral %.15e to the pthread 0\n", rank,local_integral);
}
else
{
total_integral = local_integral;
for (int source = 1;source < size;source++)
{
MPI_Recv(&local_integral, 1, MPI_DOUBLE, source, 0, MPI_COMM_WORLD,MPI_STATUS_IGNORE);
printf("The pthread 0 has received an integral %.15e from the %dth pthread of %d pthreads\n",
local_integral,source,size);
total_integral += local_integral;
}
}
end = MPI_Wtime();
if (rank == 0)
{
printf("The result is %.15e\n", total_integral);
printf("The elapsed time : %lf s\n",(end - start));
}
MPI_Finalize();
return 0;
}
MPI计算积分
最新推荐文章于 2021-05-18 11:16:53 发布