[英]How does this algorithm to calculate square root work?
I have found a piece of mathematical code to compute the square root of a real value.我找到了一段数学代码来计算实数值的平方根。 I obviously understand the code itself, but I must say that I badly understand the math logic of that algorithm.
我显然理解代码本身,但我必须说我非常理解该算法的数学逻辑。 How does it work exactly?
它是如何工作的?
inline
double _recurse(const double &_, const double &_x, const double &_y)
{ double _result;
if(std::fabs(_y - _x) > 0.001)
_result = _recurse(_, _y, 0.5 * (_y + _ / _y));
else
_result = _y;
return _result;
}
inline
double sqrt(const double &_)
{ return _recurse(_, 1.0, 0.5 * (1.0 + _)); }
Assume that you want to compute √a
and have found an approxmation x
.假设您要计算
√a
并找到一个近似值x
。 You want to improve that approximation by adding some correction δ
to x
.您想通过向
x
添加一些校正δ
来改进该近似值。 In other terms, you want to establish换句话说,你想建立
x + δ = √a
or或者
(x + δ)² = x² + 2xδ + δ² = a
If you neglect the small term δ²
, you can solve for δ
and get如果忽略小项
δ²
,则可以求解δ
并得到
δ ~ (a - x²)/(2x)
and finally最后
x + δ ~ (a + x²)/(2x) = (a/x + x)/2.
This process can be iterated and converges very quickly to √a
.这个过程可以迭代并很快收敛到
√a
。
Eg for a=2
and the initial value x=1
, we get the approximations例如对于
a=2
和初始值x=1
,我们得到近似值
1, 3/2, 17/12, 577/408, 665857/470832, ...
and the corresponding squares,和相应的方块,
1, 2.25, 2.00694444..., 2.0000060073049..., 2.0000000000045...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.