Skip to content

Instantly share code, notes, and snippets.

@WangYihang
Created March 8, 2021 14:14
Show Gist options
  • Save WangYihang/4326d44a9fffa1e1c3cdd41529e004e9 to your computer and use it in GitHub Desktop.
Save WangYihang/4326d44a9fffa1e1c3cdd41529e004e9 to your computer and use it in GitHub Desktop.
def bisection(f, a, b, delta, max_steps):
l = a
r = b
for _ in range(max_steps):
p = (l + r) / 2
print("[{:02d}] {} {} {}".format(_, l, p, r))
s = f(p) * f(l)
if s < 0:
r = p
elif s > 0:
l = p
else:
return p
if ((r - l) / 2) < delta:
return p
def f(x):
return x ** 2 - 2
print(bisection(f, 0, 2, 10 ** (-9), 100))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment