|
| 1 | +from typing import Callable |
| 2 | + |
| 3 | +import numpy as np |
| 4 | + |
| 5 | + |
| 6 | +def euler_modified( |
| 7 | + ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float |
| 8 | +) -> np.array: |
| 9 | + """ |
| 10 | + Calculate solution at each step to an ODE using Euler's Modified Method |
| 11 | + The Euler is straightforward to implement, but can't give accurate solutions. |
| 12 | + So, they Proposed some changes to improve the accuracy |
| 13 | +
|
| 14 | + https://en.wikipedia.org/wiki/Euler_method |
| 15 | +
|
| 16 | + Arguments: |
| 17 | + ode_func -- The ode as a function of x and y |
| 18 | + y0 -- the initial value for y |
| 19 | + x0 -- the initial value for x |
| 20 | + stepsize -- the increment value for x |
| 21 | + x_end -- the end value for x |
| 22 | +
|
| 23 | + >>> # the exact solution is math.exp(x) |
| 24 | + >>> def f1(x, y): |
| 25 | + ... return -2*x*(y**2) |
| 26 | + >>> y = euler_modified(f1, 1.0, 0.0, 0.2, 1.0) |
| 27 | + >>> y[-1] |
| 28 | + 0.503338255442106 |
| 29 | + >>> import math |
| 30 | + >>> def f2(x, y): |
| 31 | + ... return -2*y + (x**3)*math.exp(-2*x) |
| 32 | + >>> y = euler_modified(f2, 1.0, 0.0, 0.1, 0.3) |
| 33 | + >>> y[-1] |
| 34 | + 0.5525976431951775 |
| 35 | + """ |
| 36 | + N = int(np.ceil((x_end - x0) / step_size)) |
| 37 | + y = np.zeros((N + 1,)) |
| 38 | + y[0] = y0 |
| 39 | + x = x0 |
| 40 | + |
| 41 | + for k in range(N): |
| 42 | + y_get = y[k] + step_size * ode_func(x, y[k]) |
| 43 | + y[k + 1] = y[k] + ( |
| 44 | + (step_size / 2) * (ode_func(x, y[k]) + ode_func(x + step_size, y_get)) |
| 45 | + ) |
| 46 | + x += step_size |
| 47 | + |
| 48 | + return y |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == "__main__": |
| 52 | + import doctest |
| 53 | + |
| 54 | + doctest.testmod() |
0 commit comments