Calculate the root of an equation by the Pegasus 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)
| 157 | |
| 158 | |
| 159 | def pegasus(f, a, b, toler, iter_max): |
| 160 | """Calculate the root of an equation by the Pegasus method. |
| 161 | |
| 162 | Args: |
| 163 | f (function): equation f(x). |
| 164 | a (float): lower limit. |
| 165 | b (float): upper limit. |
| 166 | toler (float): tolerance (stopping criterion). |
| 167 | iter_max (int): maximum number of iterations (stopping criterion). |
| 168 | |
| 169 | Returns: |
| 170 | root (float): root value. |
| 171 | iter (int): number of iterations used by the method. |
| 172 | converged (boolean): flag to indicate if the root was found. |
| 173 | """ |
| 174 | fa = f(a) |
| 175 | fb = f(b) |
| 176 | x = b |
| 177 | fx = fb |
| 178 | |
| 179 | converged = False |
| 180 | for i in range(0, iter_max + 1): |
| 181 | delta_x = -fx / (fb - fa) * (b - a) |
| 182 | x += delta_x |
| 183 | fx = f(x) |
| 184 | |
| 185 | print(f"i = {i:03d},\tx = {x:+.4f},\t", end="") |
| 186 | print(f"fx = {fx:+.4f},\tdx = {delta_x:+.4f}") |
| 187 | |
| 188 | if math.fabs(delta_x) <= toler and math.fabs(fx) <= toler: |
| 189 | converged = True |
| 190 | break |
| 191 | |
| 192 | if fx * fb < 0: |
| 193 | a = b |
| 194 | fa = fb |
| 195 | else: |
| 196 | fa = fa * fb / (fb + fx) |
| 197 | |
| 198 | b = x |
| 199 | fb = fx |
| 200 | |
| 201 | root = x |
| 202 | return root, i, converged |
| 203 | |
| 204 | |
| 205 | def muller(f, a, c, toler, iter_max): |