牛顿迭代法求平方根
2018-2-1 03:57:48 Author: rmb122.com(查看原文) 阅读量:0 收藏

牛顿法可以求一些非线性方程的近似解. 而对于求平方根,  可以将 $y = \sqrt{x}$ 化成方程 $x^2 - a = 0$ 中求 $x$ 的值, $x$ 即为 $a$ 的开根号, 根据牛顿法定义, 可以写出以下程序

 1double mysqrt(const double input, double approximation = 1, unsigned int iterations = 8)
 2{
 3	if (input < 0 || approximation <= 0)
 4	{
 5		throw std::runtime_error("Input and approximation should bigger than zero.");
 6	}
 7
 8	double y;
 9	double k;
10	for (unsigned int i = 0; i < iterations; ++i)
11	{	
12		y = approximation * approximation - input;
13		k = 2 * approximation;
14		approximation = -y / k + approximation;	
15		//approximation = -(approximation * approximation - input) / (2 * approximation) + approximation;
16	}
17        return approximation;
18}

画成图差不多这样, 是一个不断迭代, 精度越来越高的过程.
实际运行的结果, 在迭了8代的情况, 已经差不多已经到double类型的极限了.


文章来源: https://rmb122.com/2018/01/31/%E7%89%9B%E9%A1%BF%E8%BF%AD%E4%BB%A3%E6%B3%95%E6%B1%82%E5%B9%B3%E6%96%B9%E6%A0%B9/
如有侵权请联系:admin#unsafe.sh