I am trying to write a binary search function to find the root of function fun in the interval [,]:
Here is what I have which is close but missing the mark:
def binarySearchIter(fun, start, end, eps=1e-10):
'''
fun: funtion to fund the root
start, end: the starting and ending of the interval
eps: the machine-precision, should be a very small number like 1e-10
return the root of fun between the interval [start, end]
'''
root = (start + end)/2
print(root)
answer=fun(root)
if abs(answer) <= eps:
print(root)
return root
elif answer - eps > 0:
binarySearchIter(fun, start, root, eps=1e-10)
else:
binarySearchIter(fun, root, end, eps=1e-10)
Here is the function I am using to test:
def f(x):
return x ** 2 - 2
When I run: binarySearchIter(f, -3, 0, eps = 1e-10) I expect an answer of: -1.4142135623842478, however, root converges to -3 until it times out.
when I run binarySearchIter(f, 0, 3, eps = 1e-10) I am getting the correct answer of 1.4142135623842478.
I am obviously missing something that is making the function break depending on whether it gets (-3, 0) or (3,0).
Thank you for your help.