基本算法 逐步縮小函數(shù)值異號的范圍 最后逼近最終解
所有線程計算中地位相同 計算范圍與self號相應的區(qū)段值 把x較小值做為解 只支持單個解
lx做為計算范圍和終止條件 最后 由主線程顯示結果
1.2.#include "mpi.h"
3.
-
•#include <stdio.h>
•#include <stdlib.h> •
•#define END 999999 •#define CON 1 •#define RES 2 •//calculation values •#define OST 0.000001 •#define IL 0.5 •#define IH 1.5 •#define THD 0.0001 •float func(float x) { • //any function • return (x*x-1); •}
•int main(int argc,char *argv[]) { • int self,size; • MPI_Init(&argc,&argv);
• MPI_Comm_rank(MPI_COMM_WORLD,&self);
• MPI_Comm_size(MPI_COMM_WORLD,&size);
• MPI_Request r;
• MPI_Status s;
• float lx=IL,hx=IH;//end point value • float res=END; • float *data=(float *)malloc(size*sizeof(float));//for gather • while(((hx-lx)/size>THD)&&(END!=lx)) { • res=END;
• float step=(hx-lx)/size; • lx=lx+step*(self);
• hx=lx+step-OST;
• float lv=func(lx); • float hv=func(hx); • if(lv*hv<0) { • //continue calculation • } else { • if(0==lv) { • //end and mark to pass low to root • res=lx;
• } else if(0==hv) { • //end and mark to pass high to root • res=hx;
• } else { • //wait for a new lx hx • }
• lx=END;
• }
• //gather all lx • MPI_Allgather(&lx,1,MPI_FLOAT,data,1,MPI_FLOAT,MPI_COMM_WORLD);
• int prc=END; • for(int i=0;i<size;++i) { • if(END!=data[i]) { • prc=i;
• lx=data[i];
• }
• }
• if(END==prc) {//all ends • if(END!=res) {//send res to root • MPI_Ssend(&res,1,MPI_FLOAT,0,0,MPI_COMM_WORLD);
• }
• } else { • MPI_Bcast(&hx,1,MPI_FLOAT,prc,MPI_COMM_WORLD);
• }
• }
• if(0==self) {//show result • if(END==lx) { • MPI_Recv(&lx,1,MPI_FLOAT,MPI_ANY_SOURCE,0,MPI_COMM_WORLD,&s);
• for(int i=0;i<size;++i) { • if(END!=data[i]) { • lx=data[i];
• }
• }
• } else { • lx=(hx+lx)/2;
• }
• printf("result %f \n",lx); • }
• free(data);
• MPI_Finalize(); 本文出自:億恩科技【www.allwellnessguide.com】
服務器租用/服務器托管中國五強!虛擬主機域名注冊頂級提供商!15年品質(zhì)保障!--億恩科技[ENKJ.COM]
|