Advertisement
ss1030

square_root_bisection

Jun 22nd, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.52 KB | None | 0 0
  1. x = 25
  2. epsilon = 0.01 #how close we want to get
  3. numGuesses = 0 #just keeps track
  4. low = 0.0 #low end of range to check
  5. high = x #high end
  6. ans = (high + low)/2.0 #initial guess in the middle
  7.  
  8. while abs(ans**2 - x) >= epsilon:
  9.     print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans))
  10.     numGuesses += 1
  11.     if ans**2 < x:
  12.         low = ans
  13.     else:
  14.         high = ans
  15.     ans = (high + low)/2.0
  16. print('numGuesses = ' + str(numGuesses))
  17. print(str(ans) + ' is close to square root of ' + str(x))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement