MPI并行计算与矩阵1

#include<stdio.h>
#include<mpi.h>
#include<math.h>
long n,
     i;
double sum,
	pi,
	mypi,
	x,
	h;
int group_size,my_rank;
int main(argc,argv)
int argc;
char *argv[];
{
int group_size,my_rank;
MPI_Status status;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
MPI_Comm_size(MPI_COMM_WORLD,&group_size);
n=20;
MPI_Bcast(&n,1,MPI_LONG,0,MPI_COMM_WORLD);
h=1.0/(double)n;
sum=0.0;
for(i=my_rank+1;i<=n;i+=group_size)
{
printf("i=%ld,processor=%d\n",i,my_rank);
x=h*(i-0.5);
sum=sum+4.0/(1.0+x*x);
}
mypi=h*sum;
printf("the rank %ld,calculate mypi=%lf\n",my_rank,mypi);
MPI_Reduce(&mypi,&pi,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
if(0==my_rank)
 printf("pi is :%lf\n",pi);
fflush(stdout);
MPI_Finalize();
return 0;
}

In order calculate pi

1)Every processor calculate part of pi

Then use MPI_Reduce() to sum all of each part

see the code above


2) If we remove the clause:if(0==my_rank), what will happen?

We see that each clause was run 4 times, and only when my_rank equal to 0, pi=3.14 otherwise it equals to 0.00!


any question?


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值