Sqrt(x) 牛顿迭代法

为了实现sqrt(x),可以将问题看成是求解\(x^2-y=0\) ,即sqrt(y)=x;
牛顿法是求解方程的近似方法,给定初始点\((x0,f(x0))\),迭代公式为:

#include <iostream>
#include <math.h>
using namespace std;

class Solution {
public:
	int sqrt(int x) {
		double x0 = 1;
		double y0 = 1 - x ;
		double z = x0 - y0 / 2*x0;
		while (abs(y0)>0.3 ){
			y0 = x0*x0 - x;
			z = x0 - y0/(2*x0);
			x0 = z;
			//cout << z << endl;
		}
		return int(x0);
	}
};

int main()
{
	Solution s;
	cout << s.sqrt(2147395599);
}
posted @ 2015-03-04 20:02  clq.lib  阅读(584)  评论(0编辑  收藏  举报