fork download
  1. def binsearch_sqrt(num):
  2. low = 1
  3. high = num
  4. guess = low + (high - low) / 2
  5. count = 0
  6. while guess != low and guess != high:
  7. sqr = guess * guess
  8.  
  9. if sqr == num:
  10. break
  11. elif(sqr < num):
  12. low = guess
  13. else:
  14. high = guess
  15.  
  16. guess = low + (high - low) / 2
  17. count += 1
  18.  
  19. else:
  20. if abs(low * low - num) < abs(high * high - num):
  21. guess = low
  22. else:
  23. guess = high
  24. return count, guess
  25.  
  26. def print_result(num, count, guess):
  27. print(count, 'iterations')
  28. print(num, '~=', guess * guess)
  29. print(num**0.5, '~=', guess)
  30. print()
  31.  
  32. print_result(2, *binsearch_sqrt(2))
  33. print_result(9, *binsearch_sqrt(9))
Success #stdin #stdout 0.02s 27712KB
stdin
Standard input is empty
stdout
52 iterations
2 ~= 2.0000000000000004
1.4142135623730951 ~= 1.4142135623730951

1 iterations
9 ~= 9.0
3.0 ~= 3.0