Skip to content

Instantly share code, notes, and snippets.

@PhDP
Created June 24, 2013 18:19
Show Gist options
  • Save PhDP/5852225 to your computer and use it in GitHub Desktop.
Save PhDP/5852225 to your computer and use it in GitHub Desktop.
Bisection algorithm in Python (to compare with the Haskell version).
# bisection(lambda x: x**2 - 2.0, 0, 100, 1e-15)
def bisection(f, a, b, err):
if err < 1e-15 or abs(b - a) / 2 < err:
return None
if a > b:
a, b = b, a
m = (b + a) / 2.0
while (b - a) / 2.0 > err and f(m) != 0.0:
if f(a) * f(m) < 0.0:
b = m
elif f(m) * f(b) < 0.0:
a = m
else:
return None
m = (b + a) / 2.0
return m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment