Finding Square Root: Examples of Guess & Check Algorithm




"Guess and Check" - The phrase itself says that we will guess the answer and check, if condition is satisfied, that guess is our answer, else iterate.

An example for this can be, lets say we want to find square root of any perfect square.


#ask user for the number whose square root is to be found
x = int(raw_input('Enter an integer : ')) 
if x < 0: #if the number entered by user was negative
    print 'Square of any number cannot be negative'
else:
    ans = 0
     
    #following while loop checks if square of our guess exceeds the actual number
    while ans**2 < abs(x):  #abs() is explained below
        ans = ans + 1 #iterating 'ans'
     
    #if square of ans is not equals to actual number, then x is not a perfect square
    if ans**2 != abs(x):
        print(str(x) + ' is not a perfect square')
    else:
        print('Square root of ' + str(x) + ' is ' + str(ans))

Output:
Enter an integer: -25
Square of any number cannot be negative
>>>
Enter an integer : 25
Square root of 25 is 5
>>>
Enter an integer : 24
24 is not a perfect square


How abs()works:

>>> abs(10)
10
>>> abs(-10)
10
>>> abs(10.11)
10.11
>>> abs(-10.11)
10.11
>>> abs(0.003)
0.003
>>> abs(-0.003)
0.003

How to find Square Root of number that is not a perfect square?

For this we will need the accuracy upto what decimal points do we need the answer.


x = 25 #we are finding square root of 25
epsilon = 0.01 #used for accuracy. See the condition in While Loop
step = epsilon**2 #used to increment our guess 'ans'
numGuesses = 0
ans = 0.0
while (abs(ans**2 - x)) >= epsilon and ans <= x:
    ans += step # same as 'ans = ans+step'
    numGuesses += 1
print('numGuesses = ' + str(numGuesses))
if abs(ans**2-x) >= epsilon:
    print('Failed on square root of ' + str(x))
else:
    print(str(ans) + ' is close to the square root of ' + str(x))

Output:
numGuesses = 49990
4.999 is close to the square root of 25


Note:
This is a part of what I learn in an online Open Course Ware offered by MIT on edX
Its for my personal reference & also for those who have missed the course.
You too can enroll yourself on edX (if they are still offering the course MITx 6.00x)