An algorithm similar to Binary Search that finds the roots of a function f(x).
- Assuming f(x) is continous, select a range
[lo,hi]
such that f(lo
) has an opposite sign to f(hi
) - Get the midpoint as
mid = (lo + hi)/2
and compute f(mid
) - If f(
mid
) = 0, then we've found a root - Otherwise, set
mid
as the newlo
orhi
and repeatmid
islo
if it has the same sign aslo
, elsehi
loSign = getSign(f(lo))
while (hi-lo)/2 > threshold # limit iterations to prevent infinite loop
mid = (lo + hi)/2
midSign = getSign(f(mid))
if midSign == 0:
return mid
else if midSign == loSign:
lo = mid
else:
hi = mid