Run an example 'Solutions: Bisection'.
()
| 57 | |
| 58 | @print_docstring |
| 59 | def example_solution_bisection(): |
| 60 | """Run an example 'Solutions: Bisection'.""" |
| 61 | # Bisection method (find roots of an equation) |
| 62 | # Pros: |
| 63 | # It is a reliable method with guaranteed convergence; |
| 64 | # It is a simple method that searches for the root by employing a |
| 65 | # binary search; |
| 66 | # There is no need to calculate the derivative of the function. |
| 67 | # Cons: |
| 68 | # Slow convergence; |
| 69 | # It is necessary to enter a search interval [a, b]; |
| 70 | # The interval reported must have a signal exchange, f (a) * f (b)<0. |
| 71 | |
| 72 | def f(x): |
| 73 | return 2 * x ** 3 - math.cos(x + 1) - 3 |
| 74 | |
| 75 | a = -1.0 |
| 76 | b = 2.0 |
| 77 | toler = 0.01 |
| 78 | iter_max = 100 |
| 79 | |
| 80 | print("Inputs:") |
| 81 | print(f"a = {a}") |
| 82 | print(f"b = {b}") |
| 83 | print(f"toler = {toler}") |
| 84 | print(f"iter_max = {iter_max}") |
| 85 | |
| 86 | print("Execution:") |
| 87 | root, i, converged = solutions.bisection(f, a, b, toler, iter_max) |
| 88 | |
| 89 | print("Output:") |
| 90 | print(f"root = {root:.5f}") |
| 91 | print(f"i = {i}") |
| 92 | print(f"converged = {converged}") |
| 93 | |
| 94 | |
| 95 | @print_docstring |