c++ - Finding square root without using sqrt function? -
I was searching the algorithm to know the square root without using the SQLRunction function and then tried to put it in programming. I end this working code in C ++
#include & lt; Iostream & gt; using namespace std; Double SqrtNumber (double number) {double low_bound = 0; Double upper_bound = num; Double tap = 0; / * One has edited this line / / int nCount = 50; Whereas (ncount! = 0) {temp = (lower_bound + upper_bound) / 2; If (temp * temp == num) {return temp; } And if (temp * temp> num) {upper_bound = temp; } Else {lower_bound = temp; } NCount--; } Return temporary; } Int main () {double num; Cout & lt; & Lt; "Enter number \ n"; CIN & gt; & Gt; Number; If (num & lt; 0) {cout & lt; & Lt; "Error: negative number!"; Return 0; Cout & lt; & Lt; "Square roots are: +" & lt; Sqrtnum (num) and & lt; & Lt; "And -" & lt; & Lt; Sqrtnum (num); Return 0; } Now the problem is initializing the number of ncount in the declaration (here it is 50). For example, there are 22 iterations to detect the square root of 36, so if no problem finding more than 50 iterations in finding the square root of 15625, then it will return the value of temp after 50 iterations. Please give a solution for this.
Your algorithm is very bad. There is a better algorithm, which requires a maximum of 6 iterations, so that maximum accuracy can be obtained for two digits:
#include & lt; Math.h> Double sqrt (double x) {if (x & lt; = 0) 0; // If the negative number throws an exception? Int exp = 0; X = Fraxp (X, and XP); Remove the binary exponent from x if x (xh and 1) // // we want exponent expression; X * = 2; } Double y = (1 + x) / 2; // first approximation double z = 0; While (y! = Z) {// Yes, we can compare couple here! Z = y; Y = (y + x / y) / 2; } Change ldexp (y, exp / 2); Multiplication by multiplying 2 ^ (exp / 2)} starts with algorithm 1 as the first estimate for square root value. Then, at each step, it improves the next approximation taking the average between the current value y and x / y . If y = sqrt (x) , this would be if y & gt; sqrt (x) , then x / y & lt; sqrt (x) From almost the same amount in other words, it will be very fast. UPDATE : sqrt () function has been changed to remove the binary exponent to speed up convergence on very large or very small numbers And calculate the square root by number in the [1, 4] range. For this, now frexp () to & lt; Math.h> , but it is possible to extract bits from the exponent IEEE-754 format frexp () . Using
Comments
Post a Comment