Calculate the solution of the initial-value problem (IVP). Solve the IVP from the Runge-Kutta (Order Four) method. Args: f (function): equation f(x). a (float): the initial point. b (float): the final point. n (int): number of intervals. ya (numpy.nd
(f, a, b, n, ya)
| 128 | |
| 129 | |
| 130 | def rk4(f, a, b, n, ya): |
| 131 | """Calculate the solution of the initial-value problem (IVP). |
| 132 | |
| 133 | Solve the IVP from the Runge-Kutta (Order Four) method. |
| 134 | |
| 135 | Args: |
| 136 | f (function): equation f(x). |
| 137 | a (float): the initial point. |
| 138 | b (float): the final point. |
| 139 | n (int): number of intervals. |
| 140 | ya (numpy.ndarray): initial values. |
| 141 | |
| 142 | Returns: |
| 143 | vx (numpy.ndarray): x values. |
| 144 | vy (numpy.ndarray): y values (solution of IVP). |
| 145 | """ |
| 146 | vx = np.zeros(n) |
| 147 | vy = np.zeros(n) |
| 148 | |
| 149 | h = (b - a) / n |
| 150 | x = a |
| 151 | y = ya |
| 152 | |
| 153 | k = np.zeros(4) |
| 154 | |
| 155 | vx[0] = x |
| 156 | vy[0] = y |
| 157 | |
| 158 | print(f"i = 000,\tx = {x:+.4f},\ty = {y:+.4f}") |
| 159 | |
| 160 | for i in range(0, n): |
| 161 | k[0] = h * f(x, y) |
| 162 | k[1] = h * f(x + h / 2, y + k[0] / 2) |
| 163 | k[2] = h * f(x + h / 2, y + k[1] / 2) |
| 164 | k[3] = h * f(x + h, y + k[2]) |
| 165 | |
| 166 | x = a + (i + 1) * h |
| 167 | y += (k[0] + 2 * k[1] + 2 * k[2] + k[3]) / 6 |
| 168 | |
| 169 | print(f"i = {(i+1):03d},\tx = {x:+.4f},\ty = {y:+.4f}") |
| 170 | vx[i] = x |
| 171 | vy[i] = y |
| 172 | |
| 173 | return vx, vy |
| 174 | |
| 175 | |
| 176 | def rk4_system(f, a, b, n, ya): |