Analyzing Roots

Below is a Python script that approximates the positive square root of positive integers. The algorithm makes guesses by continually averaging the upper and lower bound of a range of numbers that dynamically adjusts.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
## Number we seek the sqrt of
n = input("Find sqrt of: ") ## input() gets input from the console

## Set the bounds
upperBound = n 
lowerBound = 0

## Acceptable variation in result
delta = 0.00001

## Current guess at sqrt of n
guess = (upperBound + lowerBound) / 2.0

## Checks if guess*guess is within +/- delta of n
while guess*guess < n - delta or guess*guess > n + delta:
    ## Resets bounds according to outcome
    if guess**2 < n - delta:
        lowerBound = guess
    else:
        upperBound = guess
    guess = (upperBound + lowerBound) / 2.0

test = int(guess + 0.5) ## int() casts other number types into integers
if test**2 == n:
    guess = test

print guess

Analyze the script and determine the error that exists in it from the choices below.

×

Problem Loading...

Note Loading...

Set Loading...