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

Function regula_falsi

solutions.py:106–156  ·  view source on GitHub ↗

Calculate the root of an equation by the Regula Falsi 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 criterio

(f, a, b, toler, iter_max)

Source from the content-addressed store, hash-verified

104
105
106def regula_falsi(f, a, b, toler, iter_max):
107 """Calculate the root of an equation by the Regula Falsi method.
108
109 Args:
110 f (function): equation f(x).
111 a (float): lower limit.
112 b (float): upper limit.
113 toler (float): tolerance (stopping criterion).
114 iter_max (int): maximum number of iterations (stopping criterion).
115
116 Returns:
117 root (float): root value.
118 iter (int): number of iterations used by the method.
119 converged (boolean): flag to indicate if the root was found.
120 """
121 fa = f(a)
122 fb = f(b)
123
124 if fa * fb > 0:
125 raise ValueError("The function does not change signal at \
126 the ends of the given interval.")
127
128 if fa > 0:
129 a, b = b, a
130 fa, fb = fb, fa
131
132 x = b
133 fx = fb
134
135 converged = False
136 for i in range(0, iter_max + 1):
137 delta_x = -fx / (fb - fa) * (b - a)
138 x += delta_x
139 fx = f(x)
140
141 print(f"i = {i:03d},\tx = {x:+.4f},\t", end="")
142 print(f"fx = {fx:+.4f},\tdx = {delta_x:+.4f}")
143
144 if math.fabs(delta_x) <= toler and math.fabs(fx) <= toler:
145 converged = True
146 break
147
148 if fx < 0:
149 a = x
150 fa = fx
151 else:
152 b = x
153 fb = fx
154
155 root = x
156 return root, i, converged
157
158
159def pegasus(f, a, b, toler, iter_max):

Callers

nothing calls this directly

Calls 1

fFunction · 0.85

Tested by

no test coverage detected