2022-07-11 08:19:52 +00:00
|
|
|
from collections.abc import Callable
|
2021-10-28 20:31:32 +00:00
|
|
|
|
2019-10-21 17:19:43 +00:00
|
|
|
import numpy as np
|
|
|
|
|
|
|
|
|
2021-10-28 20:31:32 +00:00
|
|
|
def explicit_euler(
|
|
|
|
ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float
|
|
|
|
) -> np.ndarray:
|
|
|
|
"""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.
|
2019-10-21 17:19:43 +00:00
|
|
|
|
2021-10-28 20:31:32 +00:00
|
|
|
Args:
|
|
|
|
ode_func (Callable): The ordinary differential equation
|
|
|
|
as a function of x and y.
|
|
|
|
y0 (float): The initial value for y.
|
|
|
|
x0 (float): The initial value for x.
|
|
|
|
step_size (float): The increment value for x.
|
|
|
|
x_end (float): The final value of x to be calculated.
|
2019-10-21 17:19:43 +00:00
|
|
|
|
2021-10-28 20:31:32 +00:00
|
|
|
Returns:
|
|
|
|
np.ndarray: Solution of y for every step in x.
|
2019-10-21 17:19:43 +00:00
|
|
|
|
|
|
|
>>> # the exact solution is math.exp(x)
|
|
|
|
>>> def f(x, y):
|
|
|
|
... return y
|
|
|
|
>>> y0 = 1
|
|
|
|
>>> y = explicit_euler(f, y0, 0.0, 0.01, 5)
|
|
|
|
>>> y[-1]
|
|
|
|
144.77277243257308
|
|
|
|
"""
|
2022-10-12 22:54:20 +00:00
|
|
|
n = int(np.ceil((x_end - x0) / step_size))
|
|
|
|
y = np.zeros((n + 1,))
|
2019-10-21 17:19:43 +00:00
|
|
|
y[0] = y0
|
|
|
|
x = x0
|
|
|
|
|
2022-10-12 22:54:20 +00:00
|
|
|
for k in range(n):
|
2020-03-04 12:40:28 +00:00
|
|
|
y[k + 1] = y[k] + step_size * ode_func(x, y[k])
|
|
|
|
x += step_size
|
2019-10-21 17:19:43 +00:00
|
|
|
|
|
|
|
return y
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|