Question:
As shown in the title, the square root library function is not required to solve the square root of a number.
Analysis:
There are two ways to solve this problem:
Train of Thought 1: Use the binary method (the ubiquitous binary method). The upper bound is initialized to the number itself, and the lower bound is initialized to 1. In this way, use the binary method to determine the sum of squares of the intermediate numbers and compare the target numbers, modify the upper and lower bounds until the threshold value is smaller than a certain value.
Train of Thought 2: Use the Newton method (mentioned in numerical analysis), use a differential method, starting from the initial point, each iteration, solves the tangent, and then solves the intersection of the tangent and the X axis, use this intersection as the starting point for iteration. For example, to solve 24, write the function:
F (x) = x ^ 2-24
Our goal is to solve the root of this function. The first derivative of the function is:
F' (x) = 2 * x
You can select X0 = 24 as the starting point. After solving the problem, the formula for the next iteration point is as follows:
X1 =-F (x0)/F' (x0) + x0
This iteration continues until it is less than a certain threshold.
The algorithm code is as follows:
/** Square. CPP ** created on: 2012-10-4 * Author: happier */# include <iostream> # include <algorithm> # include <cstdlib> using namespace STD; # define e 0.001 // precision setting/** bipartite solution */Double bsearch (double number, int * count) {// int COUNT = 0; Double Start = 1.0; double end = number; while (true) {(* count) ++; double mid = (start + end)/2; if (mid * mid-number <= E & Mid * mid-number> =-e) return mid; If (mid * mid-number> E) End = mid; elsestart = mid;} return 0;}/** Newton Method for Solving */Double Newton (double number, int * count) {double X0 = number; double x1; while (true) {(* count) ++; X1 =-(x0 * x0-Number)/(2 * X0) + x0; if (x1 * x1-number <= E & X1 * x1-number> =-E) return x1; X0 = x1;} return 0;} int main () {int COUNT = 0; // count the number of iterations. cout <"Please input the number:" <Endl; double number; CIN> number; cout <bsearch (number, & COUNT) <Endl; cout <count <Endl; Count = 0; cout <Newton (number, & COUNT) <Endl; cout <count <Endl; return 0 ;}
Summary:
Through running, we found that the speed of the Newton method is much faster than that of the Bipartite method. For example, the solution is 30000. As long as the Newton method only has 11 iterations, the accuracy can reach 0.001, but the bipartite method requires 33 times, therefore, the Newton method is widely used for root Root analysis.