Run an example 'Solutions: Secant'.
()
| 94 | |
| 95 | @print_docstring |
| 96 | def example_solution_secant(): |
| 97 | """Run an example 'Solutions: Secant'.""" |
| 98 | # Secant method (find roots of an equation) |
| 99 | # Pros: |
| 100 | # It is a fast method (slower than Newton's method); |
| 101 | # It is based on the Newton method but does not need the derivative |
| 102 | # of the function. |
| 103 | # Cons: |
| 104 | # It may diverge if the function is not approximately linear in the |
| 105 | # range containing the root; |
| 106 | # It is necessary to give two points, 'a' and 'b' where |
| 107 | # f(a)-f(b) must be nonzero. |
| 108 | |
| 109 | def f(x): |
| 110 | return 2 * x ** 3 - math.cos(x + 1) - 3 |
| 111 | |
| 112 | a = -1.0 |
| 113 | b = 2.0 |
| 114 | toler = 0.01 |
| 115 | iter_max = 100 |
| 116 | |
| 117 | print("Inputs:") |
| 118 | print(f"a = {a}") |
| 119 | print(f"b = {b}") |
| 120 | print(f"toler = {toler}") |
| 121 | print(f"iter_max = {iter_max}") |
| 122 | |
| 123 | print("Execution:") |
| 124 | root, i, converged = solutions.secant(f, a, b, toler, iter_max) |
| 125 | |
| 126 | print("Output:") |
| 127 | print(f"root = {root:.5f}") |
| 128 | print(f"i = {i}") |
| 129 | print(f"converged = {converged}") |
| 130 | |
| 131 | |
| 132 | @print_docstring |