MCPcopy Create free account
hub / github.com/cfgnunes/numerical-methods-python / secant

Function secant

solutions.py:55–103  ·  view source on GitHub ↗

Calculate the root of an equation by the Secant 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

53
54
55def secant(f, a, b, toler, iter_max):
56 """Calculate the root of an equation by the Secant method.
57
58 Args:
59 f (function): equation f(x).
60 a (float): lower limit.
61 b (float): upper limit.
62 toler (float): tolerance (stopping criterion).
63 iter_max (int): maximum number of iterations (stopping criterion).
64
65 Returns:
66 root (float): root value.
67 iter (int): number of iterations used by the method.
68 converged (boolean): flag to indicate if the root was found.
69 """
70 fa = f(a)
71 fb = f(b)
72
73 if fb - fa == 0:
74 raise ValueError("f(b)-f(a) must be nonzero.")
75
76 if b - a == 0:
77 raise ValueError("b-a must be nonzero.")
78
79 if math.fabs(fa) < math.fabs(fb):
80 a, b = b, a
81 fa, fb = fb, fa
82
83 x = b
84 fx = fb
85
86 converged = False
87 for i in range(0, iter_max + 1):
88 delta_x = -fx / (fb - fa) * (b - a)
89 x += delta_x
90 fx = f(x)
91
92 print(f"i = {i:03d},\tx = {x:+.4f},\t", end="")
93 print(f"fx = {fx:+.4f},\tdx = {delta_x:+.4f}")
94
95 if math.fabs(delta_x) <= toler and math.fabs(fx) <= toler:
96 converged = True
97 break
98
99 a, b = b, x
100 fa, fb = fb, fx
101
102 root = x
103 return root, i, converged
104
105
106def regula_falsi(f, a, b, toler, iter_max):

Callers

nothing calls this directly

Calls 1

fFunction · 0.85

Tested by

no test coverage detected