#include <stdio.h>
#include <unistd.h>
#include "mpi.h"
typedef struct
{
float a;
float b;
int n;
}INDATA_TYPE;
void Build_derived_type(INDATA_TYPE *indata, MPI_Datatype *msg_ptr) {
int blocklen[3];
MPI_Aint disp[3];
MPI_Aint adress[4];
MPI_Datatype typelist[3];
typelist[0]=MPI_FLOAT;
typelist[1]=MPI_FLOAT;
typelist[2]=MPI_INT;
blocklen[0]=blocklen[1]=blocklen[2]=1;
MPI_Address(indata,&adress[0]);
MPI_Address(&(indata->a),&adress[1]);
MPI_Address(&(indata->b),&adress[2]);
MPI_Address(&(indata->n),&adress[3]);
disp[0]=adress[1]-adress[0];
disp[1]=adress[2]-adress[0];
disp[2]=adress[3]-adress[0];
MPI_Type_struct(3,blocklen,disp,typelist,msg_ptr);
MPI_Type_commit(msg_ptr);
}
float f(float x){
return x;
}
main(int argc, char ** argv)
{
int my_rank; /* rank of process */
int p=10; /* number of process */
int source; /* rank of sender */
int dest; /* rank of receiver */
int tag=50; /* tag of message */
int message ; /* storage for the message */
MPI_Status status; /* Return status for receive */
MPI_Request req;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
MPI_Comm_size(MPI_COMM_WORLD,&p);
int sum,i;
int x[100],y[100],datax[100],datay[100];
int q=100/p;
float totalcal=0.0,mycal=0.0,low,high,step,calstep;
INDATA_TYPE mydata;
mydata.a=0.0;
mydata.b=10.0;
mydata.n=1000;
MPI_Datatype mytype;
Build_derived_type(&mydata,&mytype);
MPI_Bcast(&mydata,1,mytype,0,MPI_COMM_WORLD);
step=(mydata.b-mydata.a)/p;
low=mydata.a + my_rank*step;
high=low+step;
calstep=step/mydata.n;
for(i=0;i<mydata.n;i++){
mycal+=(high-low)*f(low+calstep*i)/mydata.n;
}
printf("mycal=%f\n",mycal);
MPI_Reduce(&mycal,&totalcal,1,MPI_FLOAT,MPI_SUM,0,MPI_COMM_WORLD);
if(my_rank==0){
printf("cal=%f",totalcal);
}
MPI_Finalize();
}/* main */