from collections.abc import Callableimport numpy as npdef 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 MethodFor reference to Euler's method refer to https://en.wikipedia.org/wiki/Euler_method.Args:ode_func (Callable): The ordinary differential equationas 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.Returns:np.ndarray: Solution of y for every step in x.>>> # 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)>>> float(y[-1])144.77277243257308"""n = int(np.ceil((x_end - x0) / step_size))y = np.zeros((n + 1,))y[0] = y0x = x0for k in range(n):y[k + 1] = y[k] + step_size * ode_func(x, y[k])x += step_sizereturn yif __name__ == "__main__":import doctestdoctest.testmod()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。
1. Open source ecosystem
2. Collaboration, People, Software
3. Evaluation model