The algorithm is as follows:
1. Guess the square root of a required number
2. Using the original number/guessing number
3. Use the value of the calculated step 2 and the average of the guessed number
4. Step 3 Gets the value for the new Guess value
5. Determine if the new guess value is the same as the original guess value, the same jump to step 2, the difference is that the guess value is the square root of the original number
# same as different in computer, reference floating point number same method
Python source code is as follows:
Import Math
From math import fabs
Num_be = input ("Please enter number with solve Square")
while (not Num_be.isdigit ()): #保证输入的为整数
Print ("Please enter Number")
Num_be = input ("Please enter number with solve Square")
Num_float = float (num_be)
Guess = input ("Please enter guess number")
while (not Guess.isdigit ()): #保证输入的为整数
Print ("Please enter Number")
Guess = input ("Please enter guess number")
Guess_float = float (guess)
Precision = float (input ("Please enter the precision")
Count = 0 #记录循环多少次
befor = 0 #前一个猜测值
Sum =0
while (Fabs (guess_float-befor) > Precision): #使用绝对值防止, where negative values are less than precision
befor = Guess_float
Guess_float = ((num_float/guess_float) + guess_float)/2
Count + = 1
Print ("Use Count:", count)
Print ("The", Num_float, "Square is:", guess_float)
Python Example--Babylon square root algorithm