Python/maths/explicit_euler.py
matkosoric 7f04e5cd34
contribution guidelines checks (#1787)
* spelling corrections

* review

* improved documentation, removed redundant variables, added testing

* added type hint

* camel case to snake case

* spelling fix

* review

* python --> Python # it is a brand name, not a snake

* explicit cast to int

* spaces in int list

* "!= None" to "is not None"

* Update comb_sort.py

* various spelling corrections in documentation & several variables naming conventions fix

* + char in file name

* import dependency - bug fix

Co-authored-by: John Law <johnlaw.po@gmail.com>
2020-03-04 13:40:28 +01:00

41 lines
898 B
Python

import numpy as np
def explicit_euler(ode_func, y0, x0, step_size, 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) / step_size))
y = np.zeros((N + 1,))
y[0] = y0
x = x0
for k in range(N):
y[k + 1] = y[k] + step_size * ode_func(x, y[k])
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()