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.
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.
|#||Guess||Difference ( Guess2 - 123456 )|
Posted by Koder Dojo
Welcome to Koder Dojo. I wrote this post while attending a free online course in Python from edX, called Introduction to Computer Science and Programming Using Python. I highly recommend the course! Guess and check programs were one of the first concepts taught during the course. The course also introduced the Babylonian Method, which I later learned via Wikipedia was a derivative of Newton's Method.