[LeetCode]Sqrt(x)
来源:互联网 发布:改变世界的九大算法 编辑:程序博客网 时间:2024/05/22 07:08
题目描述
Implement int sqrt(int x)
.
Compute and return the square root of x.
求x的平方根解题思路
使用牛顿法来求解:
牛顿迭代法(Newton's method)又称为牛顿-拉夫逊方法(Newton-Raphson method),它是牛顿在17世纪提出的一种在实数域和复数域上近似求解方程的方法。多数方程不存在求根公式,因此求精确根非常困难,甚至不可能,从而寻找方程的近似根就显得特别重要。方法使用函数f(x)的泰勒级数的前面几项来寻找方程f(x) = 0的根。牛顿迭代法是求方程根的重要方法之一,其最大优点是在方程f(x) = 0的单根附近具有平方收敛,而且该法还可以用来求方程的重根、复根。另外该方法广泛用于计算机编程中。
设r是f(x) = 0的根,选取x0作为r初始近似值,过点(x0,f(x0))做曲线y = f(x)的切线L,L的方程为y = f(x0)+f'(x0)(x-x0),求出L与x轴交点的横坐标 x1 = x0-f(x0)/f'(x0),称x1为r的一次近似值。
过点(x1,f(x1))做曲线y = f(x)的切线,并求该切线与x轴交点的横坐标 x2 = x1-f(x1)/f'(x1),称x2为r的二次近似值。重复以上过程,得r的近似值序列,其中x(n+1)=x(n)-f(x(n))/f'(x(n)),称为r的n+1次近似值,上式称为牛顿迭代公式。
根据牛顿迭代的原理,可以得到以下的迭代公式:X(n+1)=[X(n)+p/Xn]/2
设r是f(x) = 0的根,选取x0作为r初始近似值,过点(x0,f(x0))做曲线y = f(x)的切线L,L的方程为y = f(x0)+f'(x0)(x-x0),求出L与x轴交点的横坐标 x1 = x0-f(x0)/f'(x0),称x1为r的一次近似值。
过点(x1,f(x1))做曲线y = f(x)的切线,并求该切线与x轴交点的横坐标 x2 = x1-f(x1)/f'(x1),称x2为r的二次近似值。重复以上过程,得r的近似值序列,其中x(n+1)=x(n)-f(x(n))/f'(x(n)),称为r的n+1次近似值,上式称为牛顿迭代公式。
根据牛顿迭代的原理,可以得到以下的迭代公式:X(n+1)=[X(n)+p/Xn]/2
代码
/** * 使用牛顿法求解平方根 * @param x * @return */public static int sqrt(int x) {double g = x;while (Math.abs(g * g - x) > 0.000001) {g = (g + x / g) / 2;}return (int) g;}
0 0
- LeetCode: Sqrt(x)
- LeetCode sqrt(x)
- [Leetcode] Sqrt(x)
- LeetCode :Sqrt(x)
- leetcode 53: Sqrt(x)
- [LeetCode] Sqrt(x)
- Leetcode 69 sqrt(x)
- [Leetcode] Sqrt(x)
- leetcode:Sqrt(x)
- 【leetcode】sqrt(int x)
- [LeetCode]Sqrt(x)
- [leetcode]Sqrt(x)
- LeetCode-Sqrt(x)
- [leetcode] Sqrt(x)
- [leetcode] Sqrt(x)
- LeetCode - Sqrt(x)
- leetcode之sqrt(x)
- LeetCode | Sqrt(x)
- ppp拨号过程
- Shell编写脚本的笔记
- springMVC学习笔记一(hello world)
- MongoDB基本使用
- 存储过程之游标
- [LeetCode]Sqrt(x)
- HDU1245:Saving James Bond(Floyd)
- php 简单的二分法查找
- 在C#中使用官方驱动操作MongoDB
- springMVC学习笔记二(dispatcherServlet)
- 关于网上盛传的iPhone锁屏界面的设计
- 【PAT (Advanced Level)】1049. Counting Ones (30)
- Linux命令 tail 加过滤功能
- sgu111 (大整数开方)