sqrt的实现-牛顿迭代法和二分法对比
程序员文章站
2022-06-03 12:22:04
...
1. 二分法实现sqrt()
#include<iostream>
#include<cmath>
using namespace std;
#define eps 1e-2
float sqrt(float n)
{
if(n < 0) return 0;
float mid,last;
float low,up;
low = 0,up = n;
mid=(low + up)/2;
do{
if(mid*mid >n)
up = mid;
else
low = mid;
last = mid;
mid = (up + low)/2;
}while(abs(mid-last)>eps);
return mid;
}
int main(){
cout<<"sqrt(65535) is "<<sqrt(65535)<<endl;
return 0;
}
2. 牛顿迭代法实现sqrt()
#include<iostream>
#include<cmath>
using namespace std;
#define eps 1e-2
float sqrt(float x)
{
float val = x;//最终
float last;//保存上一个计算的值
do
{
last = val;
val =(val + x/val) / 2;
}while(abs(val-last) > eps);
return val;
}
int main(){
cout<<"sqrt(65535) is "<<sqrt(65535)<<endl;
return 0;
}
参考链接:
上一篇: nmcli命令详解
下一篇: 电击治网瘾调查:孩子烤焦皮肤生不如死