Calculate numeric solution at each step to an ODE using Euler's Method For reference to Euler's method refer to https://en.wikipedia.org/wiki/Euler_method. Args: ode_func (Callable): The ordinary differential equation as a function of x and y. y0 (float): The i
(
ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float
)
| 4 | |
| 5 | |
| 6 | def explicit_euler( |
| 7 | ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float |
| 8 | ) -> np.ndarray: |
| 9 | """Calculate numeric solution at each step to an ODE using Euler's Method |
| 10 | |
| 11 | For reference to Euler's method refer to https://en.wikipedia.org/wiki/Euler_method. |
| 12 | |
| 13 | Args: |
| 14 | ode_func (Callable): The ordinary differential equation |
| 15 | as a function of x and y. |
| 16 | y0 (float): The initial value for y. |
| 17 | x0 (float): The initial value for x. |
| 18 | step_size (float): The increment value for x. |
| 19 | x_end (float): The final value of x to be calculated. |
| 20 | |
| 21 | Returns: |
| 22 | np.ndarray: Solution of y for every step in x. |
| 23 | |
| 24 | >>> # the exact solution is math.exp(x) |
| 25 | >>> def f(x, y): |
| 26 | ... return y |
| 27 | >>> y0 = 1 |
| 28 | >>> y = explicit_euler(f, y0, 0.0, 0.01, 5) |
| 29 | >>> float(y[-1]) |
| 30 | 144.77277243257308 |
| 31 | """ |
| 32 | n = int(np.ceil((x_end - x0) / step_size)) |
| 33 | y = np.zeros((n + 1,)) |
| 34 | y[0] = y0 |
| 35 | x = x0 |
| 36 | |
| 37 | for k in range(n): |
| 38 | y[k + 1] = y[k] + step_size * ode_func(x, y[k]) |
| 39 | x += step_size |
| 40 | |
| 41 | return y |
| 42 | |
| 43 | |
| 44 | if __name__ == "__main__": |