mpi开发(三)--第一个练手程序(2007-05-27 10:13:30)
很简单,用到了MPI_Reduce函数,求解自然对数e,熟悉mpi程序的设计方法和结构,作为高性能并行计算的一个小作业。
#include <stdio.h>
#include "mpi.h"
#define N
10
//N是阶乘求和的项数
double calculate(int
x)
//该函数计算整数x的阶乘
double factorial(int k,int
l);
//计算分段k到l的阶乘倒数之和
int main(int argc, char *argv[])
{
int
nprocs,myrank;
double a =
0,b = N;
double
res0,res,a0,b0;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&nprocs);
MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
a0 = a + (myrank + 0) * (b -
a)/nprocs;
//计算本进程的积分区间
b0 = a0 + (b
- a)/nprocs -1;
res0 =
factorial(a0,b0);
MPI_Reduce(&res0,&res,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
printf("the
final result is %0.16lf",res);
MPI_Finalize();
return
0;
}
double factorial(int k,int l){
double sum =
0;
for(int i =
k;i <= l;i++){
sum = sum+1.0/calculate(i);
}
return
sum;
}
double calculate(int x)
{
int i;
int result =
1;
if (x == 0)
{ result = 1;}
else for (i
= 1;i <= x;i++) {
result = result * i;
}
return
result;
}