Example of bisection search for monotonously increasing function value


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

About the Author

IT Pro doing Eng-Fin-Eng translations

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
            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)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.