Calculate the root of an equation by the Newton method. Args: f (function): equation f(x). df (function): derivative of quation f(x). x0 (float): initial guess. toler (float): tolerance (stopping criterion). iter_max (int): maximum number of iterations (s
(f, df, x0, toler, iter_max)
| 266 | |
| 267 | |
| 268 | def newton(f, df, x0, toler, iter_max): |
| 269 | """Calculate the root of an equation by the Newton method. |
| 270 | |
| 271 | Args: |
| 272 | f (function): equation f(x). |
| 273 | df (function): derivative of quation f(x). |
| 274 | x0 (float): initial guess. |
| 275 | toler (float): tolerance (stopping criterion). |
| 276 | iter_max (int): maximum number of iterations (stopping criterion). |
| 277 | |
| 278 | Returns: |
| 279 | root (float): root value. |
| 280 | iter (int): number of iterations used by the method. |
| 281 | converged (boolean): flag to indicate if the root was found. |
| 282 | """ |
| 283 | fx = f(x0) |
| 284 | dfx = df(x0) |
| 285 | x = x0 |
| 286 | |
| 287 | print(f"i = 000,\tx = {x:+.4f},\tfx = {fx:+.4f}") |
| 288 | |
| 289 | converged = False |
| 290 | for i in range(1, iter_max + 1): |
| 291 | delta_x = -fx / dfx |
| 292 | x += delta_x |
| 293 | fx = f(x) |
| 294 | dfx = df(x) |
| 295 | |
| 296 | print(f"i = {i:03d},\tx = {x:+.4f},\t", end="") |
| 297 | print(f"fx = {fx:+.4f},\tdx = {delta_x:+.4f}") |
| 298 | |
| 299 | if math.fabs(delta_x) <= toler and math.fabs(fx) <= toler or dfx == 0: |
| 300 | converged = True |
| 301 | break |
| 302 | |
| 303 | root = x |
| 304 | return root, i, converged |