user3995169
user3995169

Reputation: 145

bisection search using max() function

Why did we use max function. Can't we straight away evaluate high to x. That would also achieve our purpose. So, how does the algorithm improves with this max() function?

x=25
epsilon=0.01
numGuesses= 0
low =0.0
high = max(1.0,x)
ans = (high+low)/ 2.0
while abs(ans**2 -x)>= epsilon:
    print 'low =', low, 'high =', high, 'ans =', ans
    numGuesses+= 1
    if ans**2 <= x:
        low= ans
    else:
        high= ans
    ans = (high+low)/2.0
print 'numGuesses =', numGuesses
print ans, 'is close to square root of', x

Upvotes: 0

Views: 990

Answers (1)

Karl Knechtel
Karl Knechtel

Reputation: 61617

The point of the code is to approximate the square root for any x value, not just for 25. We do this by setting a low and high value that we know are lower and higher, respectively, than the square root, and then doing math to get them closer to the correct value.

When x is between 0 and 1, the square root of x is greater than x itself. Therefore we can't just set high to x, because it needs to start out higher than the desired answer. But in these cases we also know that the square root of x is less than 1, so 1 will work as an initial high value. (Similarly, when x is greater than 1, the square root of x will also be greater than 1, but it will be less than x.)

Upvotes: 3

Related Questions