From b7cff04574f5288c0483040c11be3bcc2b396a32 Mon Sep 17 00:00:00 2001 From: wuminbin Date: Mon, 24 Jun 2019 18:11:07 +0800 Subject: [PATCH] better implementation for midpoint (#914) --- arithmetic_analysis/bisection.py | 4 ++-- searches/binary_search.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/arithmetic_analysis/bisection.py b/arithmetic_analysis/bisection.py index c81fa84f8..8bf3f0978 100644 --- a/arithmetic_analysis/bisection.py +++ b/arithmetic_analysis/bisection.py @@ -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]") return 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 if function(mid) == 0: return mid @@ -22,7 +22,7 @@ def bisection(function, a, b): # finds where the function becomes 0 in [a,b] us end = mid else: start = mid - mid = (start + end) / 2 + mid = start + (end - start) / 2.0 return mid diff --git a/searches/binary_search.py b/searches/binary_search.py index 1d5da9658..e658dac2a 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -45,7 +45,7 @@ def binary_search(sorted_collection, item): right = len(sorted_collection) - 1 while left <= right: - midpoint = (left + right) // 2 + midpoint = left + (right - left) // 2 current_item = sorted_collection[midpoint] if current_item == item: return midpoint