MPI计算积分

#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;

}





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值