求平方根算法
采用二分法和牛顿法
1.二分法
与二分查找类似,见代码
//二分法
double sqrt_math_newton(double x)
{
if(x < 0) return -1;
double low=(x>1?1:x), high=(x>1?x:1);
double mid =(low+high)/2;
while (abs(mid*mid - x) > 0.000001) {
if(mid*mid>x)
high=mid;
else
low=mid;
mid =(low+high)/2;
}
return mid;
}
2.牛顿法
更新步:
代码:
//牛顿法,速度比二分法快
double sqrt_math(double x)
{
if(x < 0) return -1;
double pre = x, tem = (pre + x/pre)/2;
while (abs(tem*tem - x) > 0.000001) {
tem = (tem+x/tem) / 2;
}
return tem;
}
完整代码:
#include <iostream>
using namespace std;
//牛顿法,速度比二分法快
double sqrt_math(double x)
{
if(x < 0) return -1;
double pre = x, tem = (pre + x/pre)/2;
while (abs(tem*tem - x) > 0.000001) {
tem = (tem+x/tem) / 2;
}
return tem;
}
//二分法
double sqrt_math_newton(double x)
{
if(x < 0) return -1;
double low=(x>1?1:x), high=(x>1?x:1);
double mid =(low+high)/2;
while (abs(mid*mid - x) > 0.000001) {
if(mid*mid>x)
high=mid;
else
low=mid;
mid =(low+high)/2;
}
return mid;
}
int main()
{
cout << "run my code!" << endl;
double num=9.0;
int sqrt_num=sqrt_math(num);
int sqrt_newton_num=sqrt_math_newton(num);
cout <<"sqrt_num:" <<sqrt_num<< endl;
cout <<"sqrt_newton_num:" <<sqrt_newton_num<< endl;
return 0;
}
运行结果:(https://tech.io/snippet/JMkxbSu)
参考: