已知 sqrt (2)约等于 1.414,要求不用数学库,求 sqrt (2)精确到小数点后 10 位。二分法、模拟退火算法

问题:已知 sqrt (2)约等于 1.414,要求不用数学库,求 sqrt (2)精确到小数点后 10 位。

【方法一】二分查找

double sqrt2( ){
    double low = 1.4, high = 1.5;
    const double eps = 1e-11;
    while (high - low > eps){
		double mid = (low + high) / 2;
        if (mid*mid > 2){
            high = mid;
        }
        else{
            low = mid;
        }
        mid = (high + low) / 2;
    }
    cout<<setprecision(12)<<low;
    return low;
}

【方法二】模拟退火
先定一个接近答案的初始点x,每次以固定步长在该点附近搜索,如果能找到比当前点更接近答案的点,则更新点,从该点附近重新搜索,否则缩短步长重新搜索。
循环,直至精度满足要求(步长小于精度)。

double sqrtOf2(){
	double res=1.414;
	int ix[2]={1,-1};
	const double exp=1e-10;
	double step=0.001;
	while(step>exp){
		bool flag=false;//每次循环flag都要初始化为false
		for(int i=0;i<2;i++){
			double tmp=ix[i]*step+res;
			if(abs(tmp*tmp-2)<abs(res*res-2)){//评价函数
				flag=true;
				res=tmp;
				break;
			}
		}
		if(!flag){
			step/=2;
		}
	}
	cout<<setprecision(12)<<res;
	return res;
}

你可能感兴趣的:(算法题,数据结构和算法)