dichotomy:
Dichotomous thinking is very intuitive, and have continued to do binary, but here attention to the need to set in place a precision 0, because the square root does not necessarily guarantee that prescribing depletion. Here take limit = 0.00002.
Newton's method:
Let r is f (x) = root 0, select x0 as r initial approximation, through the point (x0, F (x0)) to make the curve y = f (x) tangent L, L of the equation y = f (x0 ) + f '(x0) (x-x0), the intersection of the x-axis is obtained L abscissa x1 = x0-f (x0) / f' (x0), x1 is called a first approximation of r.
Through the point (x1, f (x1)) to make the curve y = f (x) is the tangent, the abscissa and determining the x2-axis intersection of the tangent and x is = x1-f (x1) / f '(x1), x2 is called secondary approximation of r. Repeat the above procedure to give an approximation of the sequence r, where x (n + 1) = x (n) -f (x (n)) / f '(x (n)), called r n + 1 times of approximation, the type known as Newton iterative formula.
The Newton iteration principle, possible to obtain the following iteration formula: X (n + 1) = [X (n) + p / Xn] / 2
https://blog.csdn.net/leviopku/article/details/82811478
Code:
1 #include<iostream> 2 #include<vector> 3 #include<deque> 4 #include<string> 5 #define limit 0.0002 6 using namespace std; 7 8 // 二分法 9 double my_sqrt(double n) 10 { 11 double start = 0; 12 double end = n; 13 double mid = (start+end)/2; 14 while(mid*mid>n+limit || mid*mid<n-limit) 15 { 16 mid = (start+end)/2; 17 if(mid*mid>n) 18 end = mid-1; 19 else 20 start = mid+1; 21 } 22 return mid; 23 } 24 25 // 牛顿法 26 double new_sqrt(double n) 27 { 28 double k = n; 29 while(1) 30 { 31 if(k*k<n+limit && k*k>n-limit) 32 { 33 break; 34 } 35 k = 0.5*(k+n/k); 36 } 37 return k; 38 } 39 int main(){ 40 double a = 81; 41 cout<<my_sqrt(a)<<endl; 42 cout<<new_sqrt(a)<<endl; 43 return 0; 44 }