用MPI求解梯形积分(上)
版本一:(固定a,b,n值,使用MPI6个基本函数)
#include<mpi.h>
double f(double x){
return x*x;
}
double Trap(double left_side,double right_side,int local_count,double h){
int i;
double estimate,temp;
double left1,right1;
left1=f(left_side);
right1=f(right_side);
estimate=(right1+left1)/2.0;
for(i=1;i<local_count;i++){
temp=left_side+i*h;
temp=f(temp);
estimate+=temp;
}
estimate=estimate*h;
return estimate;
}
int main(int argc,char *argv[]){
int n=1024,local_n;
int rank,size;
double a=0.0,b=3.0,h;
double local_a,local_b;
double local_sum,total_sum;
int q;
h=(b-a)/n;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&size);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
local_n=n/size;
local_a=a+rank*local_n*h;
local_b=local_a+local_n*h;
local_sum=Trap(local_a,local_b,local_n,h);
if(rank!=0){
MPI_Send(&local_sum,1,MPI_DOUBLE,0,99,MPI_COMM_WORLD);
}else{
total_sum=local_sum;
for(q=1;q<size;q++){
MPI_Recv(&local_sum,1,MPI_DOUBLE,q,99,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
total_sum+=local_sum;
}
}
if(rank==0){
printf("with a=%f b=%f n=%d ,the total_sum=%f\n",a,b,n,total_sum);
}
MPI_Finalize();
}
版本二:(可从键盘键入a,b,n,使用MPI6个基本函数)
#include<stdio.h>
#include<mpi.h>
void Get_input(int size,int rank,float* a_p,float* b_p,int* n_p){
int dest;
if(rank==0){
printf("Please Enter a,b,n:\n");
scanf("%f%f%d",a_p,b_p,n_p);
for(dest=1;dest<size;dest++){
MPI_Send(a_p,1,MPI_FLOAT,dest,99,MPI_COMM_WORLD);
MPI_Send(b_p,1,MPI_FLOAT,dest,99,MPI_COMM_WORLD);
MPI_Send(n_p,1,MPI_INT,dest,99,MPI_COMM_WORLD);
}}
else{
MPI_Recv(a_p,1,MPI_FLOAT,0,99,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
MPI_Recv(b_p,1,MPI_FLOAT,0,99,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
MPI_Recv(n_p,1,MPI_INT,0,99,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
<