递归版:
float recursion(float A, float e, float p = 1) // A为平方数,e为误差,p为A的平方根,下同
{
if (fabs(A- p*p) <= e)
{
cout << p << endl;
return p ;
}
return recursion(A, e, (p + A / p) / 2);
}
非递归版:
float funNotRecursion(float A, float e, float p = 1)
{
while (fabs(A - p*p) > e)
{
p = (p + A / p) / 2;
}
return p;
}
需添加头文件:#include<algorithm>
二分搜索版:
bool satisify2(double A, double x)
{
return x*x == A;
}
double sqrt(double A,double x = 1)
{
/*while (fabs(x*x -A) < pow(10,-5))
{
x = (x + A / x) / 2;
}*/
double lb = x, ub = A / x;
double mid = 0;
for (int i =0; i < 100; ++i)
{
mid = (lb + ub) / 2;
if (satisify2(A, x))
lb = mid;
else
ub = mid;;
}
return x;
}
二分搜索算法思想来自于《挑战程序设计竞赛----巫泽俊译》第三章,这本书可是个宝贝。
另外在cout输出二分搜索版的结果时需要设置cout输出的精度,如果不设置,好像默认是5位,设置输出精度如下:
cout << std::setprecision(15)<< sqrt(17) << endl;