Last active
January 21, 2018 09:06
-
-
Save HongfeiXu/b3489c1e1c9ba3dc98a0c88f471ae288 to your computer and use it in GitHub Desktop.
牛顿迭代法快速寻找平方根
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
/* | |
牛顿迭代法快速寻找平方根 | |
Ref: https://www.zhihu.com/question/20690553(详细介绍了牛顿-拉弗森方法的原理以及收敛的充分条件) | |
Ref: http://www.matrix67.com/blog/archives/361 | |
求根号 a,也就是求解 x^2 - a = 0 的非负解。 | |
这种算法的原理很简单,我们仅仅是不断用 (x,f(x)) 的切线来逼近方程 x^2 - a = 0 的根。 | |
根号a实际上就是x^2-a=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 | |
double NewtonsMethod(double n) | |
{ | |
if (n == 0) | |
return n; | |
int k = 10; // 控制迭代次数 | |
double result = n; | |
for (int i = 0; i < k; ++i) | |
result = (result + n / result) / 2; | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment