From a8f5e56f0afbc8fc2b950af61ea3780d0f1d99e5 Mon Sep 17 00:00:00 2001 From: Stephen Ryan <24819660+infrontoftheforest@users.noreply.github.com> Date: Fri, 18 Oct 2019 17:39:22 +0200 Subject: [PATCH 1/2] added explicit euler's method --- maths/explicit_euler.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 maths/explicit_euler.py diff --git a/maths/explicit_euler.py b/maths/explicit_euler.py new file mode 100644 index 000000000000..17e6a34da666 --- /dev/null +++ b/maths/explicit_euler.py @@ -0,0 +1,41 @@ +import numpy as np + + +def explicit_euler(f, y0, x0, h, x_end): + """ + Calculate numeric solution at each step to an ODE using Euler's Method + + https://en.wikipedia.org/wiki/Euler_method + + Arguments: + f -- The ode as a function of x and y + y0 -- the initial value for y + x0 -- the initial value for x + h -- the stepsize + x_end -- the end value for 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) + >>> y[-1] + 144.77277243257308 + """ + N = int(np.ceil((x_end - x0)/h)) + y = np.zeros((N + 1,)) + y[0] = y0 + x = x0 + + for k in range(N): + y[k + 1] = y[k] + h*f(x, y[k]) + x += h + + return y + + +if __name__ == "__main__": + import doctest + + doctest.testmod() + From 8c2e748a7c6783225ace7a275d7e805926eeee41 Mon Sep 17 00:00:00 2001 From: Stephen <24819660+infrontoftheforest@users.noreply.github.com> Date: Mon, 21 Oct 2019 17:12:05 +0000 Subject: [PATCH 2/2] update explicit_euler.py variable names --- maths/explicit_euler.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/maths/explicit_euler.py b/maths/explicit_euler.py index 17e6a34da666..9fce4e4185a6 100644 --- a/maths/explicit_euler.py +++ b/maths/explicit_euler.py @@ -1,17 +1,17 @@ import numpy as np -def explicit_euler(f, y0, x0, h, x_end): +def explicit_euler(ode_func, y0, x0, stepsize, x_end): """ Calculate numeric solution at each step to an ODE using Euler's Method https://en.wikipedia.org/wiki/Euler_method Arguments: - f -- The ode as a function of x and y + ode_func -- The ode as a function of x and y y0 -- the initial value for y x0 -- the initial value for x - h -- the stepsize + stepsize -- the increment value for x x_end -- the end value for x >>> # the exact solution is math.exp(x) @@ -22,14 +22,14 @@ def explicit_euler(f, y0, x0, h, x_end): >>> y[-1] 144.77277243257308 """ - N = int(np.ceil((x_end - x0)/h)) + N = int(np.ceil((x_end - x0)/stepsize)) y = np.zeros((N + 1,)) y[0] = y0 x = x0 for k in range(N): - y[k + 1] = y[k] + h*f(x, y[k]) - x += h + y[k + 1] = y[k] + stepsize*ode_func(x, y[k]) + x += stepsize return y