Example of bisection search for monotonously increasing function value

TrustyTony 0 Tallied Votes 515 Views Share

Here improved example based on MITx course of using the bisection method for root finding.

def find_root(x, power, epsilon):
    if not power or x < 0  and not power % 2:
        return None
    elif power < 0:
        x = 1./x
        power = -power
    low, high = min(-1, x), max(1, x)
    ans = (high + low) / 2.0
    while abs(ans**power - x)  > epsilon:
        if ans ** power < x:
            low = ans
        else:
            high = ans
        ans = (high + low) / 2.0
    return ans

r = find_root(4, 5, 1e-6)
print r, 4**(1./5), r-4**(1./5)