Both of the following code give the same result. But I'm not sure where should I put the raise statement.
def bisection(f, start, stop, eps = 1e-5, max_iteration = 100):
for __ in range(max_iteration):
half = start + (stop - start)/2
if abs(f(half)) < eps or half - start < eps:
return half
if f(half) * f(start) > 0:
start = half
else:
stop = half
else:
raise ValueError('Cannot find root in the given range')
Or
def bisection(f, start, stop, eps = 1e-5, max_iteration = 100):
for __ in range(max_iteration):
half = start + (stop - start)/2
if abs(f(half)) < eps or half - start < eps:
return half
if f(half) * f(start) > 0:
start = half
else:
stop = half
raise ValueError('Cannot find root in the given range')
bisectfrom the stdlib; it's a root-finding algorithm using bisection. The big difference is that this one uses floats.