当前位置:网站首页>LeetCode69:牛顿迭代法和二分法求解x的平方根
LeetCode69:牛顿迭代法和二分法求解x的平方根
2022-08-11 10:53:00 【哆啦k梦0219】
一.牛顿迭代法
首先随便猜一个近似值 n,然后不断令 n 等于 n 和 x/n 的平均数,迭代个六七次后 n 的值就已经相当精确了。
例如,我想求根号 2 等于多少。假如我猜测的结果为 4,虽然错的离谱,但你可以看到使用牛顿迭代法后这个值很快就趋近于根号 2 了:
( 4 + 2/ 4 ) / 2 = 2.25
( 2.25 + 2/ 2.25 ) / 2 = 1.56944..
( 1.56944..+ 2/1.56944..) / 2 = 1.42189..
( 1.42189..+ 2/1.42189..) / 2 = 1.41423..
….
这种算法的原理很简单,我们仅仅是不断用 (x, f(x))的切线来逼近方程 x^2-n=0的根。根号 n 实际上就是 x^2-n=0的一个正实根,这个函数的导数是 2x。也就是说,函数上任一点 (x,f(x)) 处的切线斜率是 2x。那么,x-f(x)/(2x) 就是一个比 x 更接近的近似值。代入 f(x)=x^2-a得到 x-(x^2-a)/(2x),也就是 (x+a/x)/2。同样的方法可以用在其它的近似值计算中。
代码如下:(近似值n取x)
class Solution {
public:
int mySqrt(int x)
{
if(x==0)
return 0;
int n = x;//n 为随便猜的值x
return int(newton(n,x));
}
double newton(double n,int x)
{
double curr = (n+x/n)/2;
if(curr == n)
{
return curr;
}
else
return newton(curr,x);
}
};二.二分法
//0-x有序,采用二分法
class Solution {
public:
int mySqrt(int x)
{
int left = 0;
int right = x;
int ans = -1;//储存符合条件:mid*mid<=x 的值
if(x==1)
return 1;
else if(x==0)
return 0;
while(right>=left)
{
int middle = left+(right-left)/2;//(left+right)/2
if(middle*middle<=x)
{
ans = middle;
left = middle+1;
}
else
{
right = middle-1;
}
}
return ans;
}
};边栏推荐
猜你喜欢

那些不用写代码也能做游戏的工具

2.MySQL ---- 修改数据库的字符集(日常小技巧)

小目标绝技 | 用最简单的方式完成Yolov5的小目标检测升级!

a sequence of consecutive positive numbers with sum s

Calculate the sum of an element of an array

悠漓带你玩转C语言(详解操作符1)

Neuropathic pain classification picture Daquan, neuropathic pain classification

数据库导出的csv文件纯数字被转为科学计数法

从零开始配置 vim(11)——插件管理

阿里云ssl证书申请,宝塔ssl证书部署
随机推荐
How to explain to my girlfriend what is cache penetration, cache breakdown, cache avalanche?
中小企业如何实施MES管理系统
云原生 · 镜像详解
How to build programming ideas and improve programming ideas
小目标绝技 | 用最简单的方式完成Yolov5的小目标检测升级!
SDUT数据库 SQL语句练习(MySQL)
论文笔记:《Time Series Generative Adversrial Networks》(TimeGAN,时间序列GAN)
阿里二面:JVM调优你会吗?
form-making爬坑笔记(jeecg项目替换表单设计器)
VMWare中安装的win10,新增其他盘符,如:E盘,F盘等
神经网络可视化有3D版本了,美到沦陷!(已开源)
Word小技巧之图表实现自动编号和更新
杰理AC632N蓝牙芯片iokey使用解析(通用MCU版)
微信小游戏是个人尝试做游戏最好的选择
Calculate the sum of an element of an array
fetch请求设置请求头错误导致无法跨域
【翻译】Drafting and Revision: Laplacian Pyramid Network for Fast High-Quality Artistic Style Transfer
logstash/filebeat只接收最近一段时间的数据
a-upload上传图片
【分享】PPT还能做成这样?你一定没见过