Newton iteration method to achieve root sign

What is Newton's iteration method

Newton's iteration method, as the name suggests, is a method of approximating the target value through iteration, and is often used in numerical analysis (such as finding the roots of non-basic functions).
Newton iteration can prove that starting from any initial point in the defined domain, it must eventually converge to the target value .

Simple understanding of Newton's iteration formula

Simplify the problem as follows: Suppose a function is given and find its zero point .
Insert picture description here
It can be seen in the figure that the abscissa of the initial point is p 0 , and the tangent line from this point intersects the ordinate at (p 1 , 0). In the next step, p 1 is taken as the basic point of the iteration, and the tangent is drawn to obtain p 2 . It can be seen intuitively that as the iteration p n gradually approaches the true zero point p, assuming that in the nth iteration, p n is exactly equal to p, then p n+1 is also equal to p, and the coordinates of the iteration will not change anymore. You can return p n as the result.
The formula of the iterative process is
pn + 1 = pn − f (pn) f ′ (pn) p_(n+1) = p_n-\frac{f(p_n)}{f^{')(p_n))pn+1=pnf(pn)f(pn)
(The slope formula can be converted)

Use Newton's iteration method to realize root sign

In fact, it is to implement the sqrt() function by yourself. If the traversal starts from 0, the efficiency is relatively low, and it is relatively troublesome to use the dichotomy. The simplest and most efficient method is Newton iteration.
Insert picture description here
First, convert the problem. Opening the root of A is equivalent to finding the function f (x) = x 2 − A f(x) = x^{2}-Af(x)=x2The root of A.
Take the derivative of the function and put it in the formula, and then you can happily wait for the result of the iteration.

Code:
ps: Integer division is used. If you want to get a floating point result, please modify the data type yourself.

int main() {
    
    
	int N;
	cin >> N;
	if (N <= 1) {
    
    
		cout << N << endl;
		return 0;
	}
    long long next = N;
    while(next > N / next) {
    
    
        next = (next + N / next) / 2;
    }
    cout << next << endl;
}

Guess you like

Origin blog.csdn.net/weixin_43867940/article/details/106011458