Skip to content

Instantly share code, notes, and snippets.

@nafu
Created February 13, 2013 11:39
Show Gist options
  • Save nafu/4944047 to your computer and use it in GitHub Desktop.
Save nafu/4944047 to your computer and use it in GitHub Desktop.
Bisection Search
x = 1234567
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))
high = 100
low = 0
ans = (high + low)/2
x = ''
print('Please think of a number between 0 and 100!')
while x != 'c':
print('Is your secret number ' + str(ans) + '?')
x = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")
if x == 'h':
high = ans
elif x == 'l':
low = ans
elif x == 'c':
print('Game over. Your secret number was: ' + str(ans))
break
else:
print('Sorry, I did not understand your input.')
continue
ans = (high + low)/2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment