Skip to content

added explicit euler's method #1394

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 21, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions maths/explicit_euler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import numpy as np


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:
ode_func -- The ode as a function of x and y
y0 -- the initial value for y
x0 -- the initial value for x
stepsize -- the increment value for x
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)/stepsize))
y = np.zeros((N + 1,))
y[0] = y0
x = x0

for k in range(N):
y[k + 1] = y[k] + stepsize*ode_func(x, y[k])
x += stepsize

return y


if __name__ == "__main__":
import doctest

doctest.testmod()