Here improved example based on MITx course of using the bisection method for root finding.
Example of bisection search for monotonously increasing function value
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)
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.