Skip to content

Commit dbf904f

Browse files
stephen-ryan-ansyspoyea
authored andcommitted
added runge-kutta (TheAlgorithms#1393)
1 parent 5c351d8 commit dbf904f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

maths/runge_kutta.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import numpy as np
2+
3+
4+
def runge_kutta(f, y0, x0, h, x_end):
5+
"""
6+
Calculate the numeric solution at each step to the ODE f(x, y) using RK4
7+
8+
https://en.wikipedia.org/wiki/Runge-Kutta_methods
9+
10+
Arguments:
11+
f -- The ode as a function of x and y
12+
y0 -- the initial value for y
13+
x0 -- the initial value for x
14+
h -- the stepsize
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 = runge_kutta(f, y0, 0.0, 0.01, 5)
22+
>>> y[-1]
23+
148.41315904125113
24+
"""
25+
N = int(np.ceil((x_end - x0)/h))
26+
y = np.zeros((N + 1,))
27+
y[0] = y0
28+
x = x0
29+
30+
for k in range(N):
31+
k1 = f(x, y[k])
32+
k2 = f(x + 0.5*h, y[k] + 0.5*h*k1)
33+
k3 = f(x + 0.5*h, y[k] + 0.5*h*k2)
34+
k4 = f(x + h, y[k] + h * k3)
35+
y[k + 1] = y[k] + (1/6)*h*(k1 + 2*k2 + 2*k3 + k4)
36+
x += h
37+
38+
return y
39+
40+
41+
if __name__ == "__main__":
42+
import doctest
43+
44+
doctest.testmod()

0 commit comments

Comments
 (0)