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)
| 104 | |
| 105 | |
| 106 | def 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 | |
| 159 | def pegasus(f, a, b, toler, iter_max): |