MPI 并行解方程


基本算法 逐步缩小函数值异号的范围 最后逼近最终解

所有线程计算中地位相同 计算范围与self号相应的区段值 把x较小值做为解 只支持单个解

lx做为计算范围和终止条件 最后 由主线程显示结果

  1. #include "mpi.h"   
  2. #include <stdio.h>   
  3. #include <stdlib.h>   
  4.   
  5. #define END 999999   
  6. #define CON 1   
  7. #define RES 2   
  8. //calculation values   
  9. #define OST 0.000001   
  10. #define IL 0.5   
  11. #define IH 1.5   
  12. #define THD 0.0001   
  13. float func(float x) {  
  14.     //any function   
  15.     return (x*x-1);  
  16. }  
  17. int main(int argc,char *argv[]) {     
  18.     int self,size;  
  19.     MPI_Init(&argc,&argv);  
  20.     MPI_Comm_rank(MPI_COMM_WORLD,&self);  
  21.     MPI_Comm_size(MPI_COMM_WORLD,&size);  
  22.     MPI_Request r;  
  23.     MPI_Status s;  
  24.     float lx=IL,hx=IH;//end point value   
  25.     float res=END;  
  26.     float *data=(float *)malloc(size*sizeof(float));//for gather   
  27.     while(((hx-lx)/size>THD)&&(END!=lx)) {  
  28.         res=END;  
  29.         float step=(hx-lx)/size;  
  30.         lx=lx+step*(self);  
  31.         hx=lx+step-OST;  
  32.         float lv=func(lx);  
  33.         float hv=func(hx);  
  34.         if(lv*hv<0) {  
  35.             //continue calculation   
  36.         } else {  
  37.             if(0==lv) {  
  38.                 //end and mark to pass low to root   
  39.                 res=lx;  
  40.             } else if(0==hv) {  
  41.                 //end and mark to pass high to root   
  42.                 res=hx;  
  43.             } else {  
  44.                 //wait for a new lx hx   
  45.             }  
  46.             lx=END;  
  47.         }  
  48.         //gather all lx   
  49.         MPI_Allgather(&lx,1,MPI_FLOAT,data,1,MPI_FLOAT,MPI_COMM_WORLD);  
  50.         int prc=END;  
  51.         for(int i=0;i<size;++i) {  
  52.             if(END!=data[i]) {  
  53.                 prc=i;  
  54.                 lx=data[i];  
  55.             }  
  56.         }  
  57.         if(END==prc) {//all ends   
  58.             if(END!=res) {//send res to root   
  59.                 MPI_Ssend(&res,1,MPI_FLOAT,0,0,MPI_COMM_WORLD);  
  60.             }  
  61.         } else {  
  62.             MPI_Bcast(&hx,1,MPI_FLOAT,prc,MPI_COMM_WORLD);  
  63.         }  
  64.     }  
  65.     if(0==self) {//show result   
  66.         if(END==lx) {  
  67.             MPI_Recv(&lx,1,MPI_FLOAT,MPI_ANY_SOURCE,0,MPI_COMM_WORLD,&s);  
  68.             for(int i=0;i<size;++i) {  
  69.                 if(END!=data[i]) {  
  70.                     lx=data[i];  
  71.                 }  
  72.             }  
  73.         } else {  
  74.             lx=(hx+lx)/2;  
  75.         }  
  76.         printf("result %f \n",lx);  
  77.     }  
  78.     free(data);  
  79.     MPI_Finalize();  
  80.     return 0;  
  81. }  

相关内容