Skip to content

Commit afeb13b

Browse files
stephen-ryan-ansyscclauss
authored andcommitted
added explicit euler's method (TheAlgorithms#1394)
* added explicit euler's method * update explicit_euler.py variable names
1 parent 313a043 commit afeb13b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

maths/explicit_euler.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import numpy as np
2+
3+
4+
def explicit_euler(ode_func, y0, x0, stepsize, x_end):
5+
"""
6+
Calculate numeric solution at each step to an ODE using Euler's Method
7+
8+
https://en.wikipedia.org/wiki/Euler_method
9+
10+
Arguments:
11+
ode_func -- The ode as a function of x and y
12+
y0 -- the initial value for y
13+
x0 -- the initial value for x
14+
stepsize -- the increment value for x
15+
x_end -- the end value for x
16+
17+
>>> # the exact solution is math.exp(x)
18+
>>> def f(x, y):
19+
... return y
20+
>>> y0 = 1
21+
>>> y = explicit_euler(f, y0, 0.0, 0.01, 5)
22+
>>> y[-1]
23+
144.77277243257308
24+
"""
25+
N = int(np.ceil((x_end - x0)/stepsize))
26+
y = np.zeros((N + 1,))
27+
y[0] = y0
28+
x = x0
29+
30+
for k in range(N):
31+
y[k + 1] = y[k] + stepsize*ode_func(x, y[k])
32+
x += stepsize
33+
34+
return y
35+
36+
37+
if __name__ == "__main__":
38+
import doctest
39+
40+
doctest.testmod()
41+

0 commit comments

Comments
 (0)