Wednesday, June 1, 2016

Bisection Search Using Python

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
x = 123
epsilon = 0.01
numGuesses = 0
low = 0.0
high = x
ans = (high + low)/2.0
while abs(ans**2 - x) >= epsilon:
    print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans))
    numGuesses += 1
    if ans**2 < x:
        low = ans
    else:
        high = ans
    ans = (high + low)/2.0
print('numGuesses = ' + str(numGuesses))
print(str(ans) + ' is close to square root of ' + str(x))

Hasil :

No comments:

Post a Comment