Created
March 8, 2021 14:14
-
-
Save WangYihang/4326d44a9fffa1e1c3cdd41529e004e9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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