Python Program to Calculate Square Roots using Babylonian Method

I need to develop a guess and check program in Python to calculate the square root of a number. In a guess and check program I provide an initial guess for the answer. The program checks to see if that guess is correct. If it is, the program is done. If not, the program generates another guess and checks to see if that guess is correct. The program continues the iterative process of guessing and checking until it finds either the exact answer or a close enough approximation to the answer.

To make the program efficient it is important to generate guesses that get closer and closer to the answer as quickly as possible. The Babylonian Method is a function that helps generate guesses that quickly converge to find the square root of a number.

The Babylonian Method states that if the previous guess, xn, is an overestimate of the square root of a number, S, then a more precise next guess, xn+1, is the average of the previous guess and the number divided by the previous guess.

xn+1 = ( xn + S / xn ) / 2

Now that I have a method of generating intelligent guesses I can create a Python program to calculate the square root of a number within a certain degree of accuracy.

number = abs(float(raw_input("Calculate square root of? ")))
guess = abs(float(raw_input("Initial guess? ")))

epsilon = 0.001

while True:
    difference = guess**2 - number
    print('{} : {}'.format(round(guess, 4), round(difference, 4)))
    if abs(difference) <= epsilon:
    guess = (guess + number / guess) / 2.0

Using this code, if I am trying to solve for the square root of 123456 with an initial guess of 600, the Python program quickly converges on an answer using the Babylonian Method. It only takes 5 tries for the Babylonian Method to provide an approximation to the square root of 123456 using my initial guess of 600. I purposely picked 600 just to show how quickly the Babylonian Method converges even when the initial guess is pretty far off.

#GuessDifference ( Guess2 - 123456 )
1 600.0 236544.0
2 402.88 38856.2944
3 354.6568 2325.4733
4 351.3784 10.7485
5 351.3631 0.0002
Posted by David Hayden
Koder Dojo
David Hayden is a professional Microsoft web developer. He mentors and tutors computer science students in C, C++, Java, and Python. In addition to writing computer science and programming tutorials at Koder Dojo, he also writes tutorials on C#, ASP.NET Core, and Azure as well as tutorials on Orchard Core.