MPI 并行解方程

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

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

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

#include "mpi.h"
#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();
	return 0;
}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值