better implementation for midpoint (#914)

This commit is contained in:
wuminbin 2019-06-24 18:11:07 +08:00 committed by John Law
parent a212efee5b
commit b7cff04574
2 changed files with 3 additions and 3 deletions

View File

@ -14,7 +14,7 @@ def bisection(function, a, b): # finds where the function becomes 0 in [a,b] us
print("couldn't find root in [a,b]") print("couldn't find root in [a,b]")
return return
else: else:
mid = (start + end) / 2 mid = start + (end - start) / 2.0
while abs(start - mid) > 10**-7: # until we achieve precise equals to 10^-7 while abs(start - mid) > 10**-7: # until we achieve precise equals to 10^-7
if function(mid) == 0: if function(mid) == 0:
return mid return mid
@ -22,7 +22,7 @@ def bisection(function, a, b): # finds where the function becomes 0 in [a,b] us
end = mid end = mid
else: else:
start = mid start = mid
mid = (start + end) / 2 mid = start + (end - start) / 2.0
return mid return mid

View File

@ -45,7 +45,7 @@ def binary_search(sorted_collection, item):
right = len(sorted_collection) - 1 right = len(sorted_collection) - 1
while left <= right: while left <= right:
midpoint = (left + right) // 2 midpoint = left + (right - left) // 2
current_item = sorted_collection[midpoint] current_item = sorted_collection[midpoint]
if current_item == item: if current_item == item:
return midpoint return midpoint