-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbisection_method.py
More file actions
76 lines (63 loc) · 2.34 KB
/
Copy pathbisection_method.py
File metadata and controls
76 lines (63 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from typing import Callable, Tuple, List, Dict
from numbers import Real
def find_root(
interval: Tuple[Real, Real],
tolerance: Real,
f: Callable[[Real], Real],
print_output: bool = False,
get_logs: bool = False
):
""" Finds the root of given function by repeatedly halving the given interval
Args:
interval (tuple(int or float, int or float)): The interval to be used find the root
tolerance (int or float): The specified maximum allowable error hat determines when to stop the iterative process of finding a root
f (Callable): The function to be used to find its root with given interval
print_output (bool): Prints the output of interval and midpoint for every iteration
get_logs (bool): Decide if to get calculations for every iteration
"""
a, b = interval
# Validate inputs
if not (isinstance(a, Real) and isinstance(b, Real)):
raise ValueError("Interval endpoints must be real numbers.")
if not isinstance(tolerance, Real):
raise ValueError("Tolerance must be a real number.")
fa = f(a)
fb = f(b)
if fa * fb > 0:
raise ValueError(
"Function must have opposite signs at interval endpoints.\n"
f"Your interval ({a}, {b}): f(a)={fa}, f(b)={fb}"
)
logs: List[Dict[str, Real]] = [] if get_logs else None
iteration = 1
try:
while abs(b - a) > tolerance:
midpoint = (a + b) / 2
fm = f(midpoint)
if get_logs:
logs.append({
"iteration": iteration,
"a": a,
"b": b,
"midpoint": midpoint,
"f(a)": fa,
"f(b)": fb,
"f(midpoint)": fm
})
if print_output:
print(
f"Iteration {iteration}: "
f"[{a:.9f}, {b:.9f}], midpoint = {midpoint:.9f}"
)
# Decide which interval to keep
if fa * fm < 0:
b = midpoint
fb = fm
else:
a = midpoint
fa = fm
iteration += 1
root = (a + b) / 2
return (root, logs) if get_logs else root
except Exception as e:
raise RuntimeError(f"Root finding failed: {e}")