MCPcopy Index your code
hub / github.com/cfgnunes/numerical-methods-python / bisection

Function bisection

solutions.py:6–52  ·  view source on GitHub ↗

Calculate the root of an equation by the Bisection method. Args: f (function): equation f(x). a (float): lower limit. b (float): upper limit. toler (float): tolerance (stopping criterion). iter_max (int): maximum number of iterations (stopping criterion).

(f, a, b, toler, iter_max)

Source from the content-addressed store, hash-verified

4
5
6def bisection(f, a, b, toler, iter_max):
7 """Calculate the root of an equation by the Bisection method.
8
9 Args:
10 f (function): equation f(x).
11 a (float): lower limit.
12 b (float): upper limit.
13 toler (float): tolerance (stopping criterion).
14 iter_max (int): maximum number of iterations (stopping criterion).
15
16 Returns:
17 root (float): root value.
18 iter (int): number of iterations used by the method.
19 converged (boolean): flag to indicate if the root was found.
20 """
21 fa = f(a)
22 fb = f(b)
23
24 if fa * fb > 0:
25 raise ValueError("The function does not change signal at \
26 the ends of the given interval.")
27
28 delta_x = math.fabs(b - a) / 2
29
30 x = 0
31 converged = False
32 for i in range(0, iter_max + 1):
33 x = (a + b) / 2
34 fx = f(x)
35
36 print(f"i = {i:03d},\tx = {x:+.4f},\t", end="")
37 print(f"fx = {fx:+.4f},\tdx = {delta_x:+.4f}")
38
39 if delta_x <= toler and math.fabs(fx) <= toler:
40 converged = True
41 break
42
43 if fa * fx > 0:
44 a = x
45 fa = fx
46 else:
47 b = x
48
49 delta_x = delta_x / 2
50
51 root = x
52 return root, i, converged
53
54
55def secant(f, a, b, toler, iter_max):

Callers

nothing calls this directly

Calls 1

fFunction · 0.85

Tested by

no test coverage detected