Skip to content

added runge-kutta #1393

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 1 commit into from
Oct 19, 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
44 changes: 44 additions & 0 deletions maths/runge_kutta.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import numpy as np


def runge_kutta(f, y0, x0, h, x_end):
"""
Calculate the numeric solution at each step to the ODE f(x, y) using RK4

https://en.wikipedia.org/wiki/Runge-Kutta_methods

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 = runge_kutta(f, y0, 0.0, 0.01, 5)
>>> y[-1]
148.41315904125113
"""
N = int(np.ceil((x_end - x0)/h))
y = np.zeros((N + 1,))
y[0] = y0
x = x0

for k in range(N):
k1 = f(x, y[k])
k2 = f(x + 0.5*h, y[k] + 0.5*h*k1)
k3 = f(x + 0.5*h, y[k] + 0.5*h*k2)
k4 = f(x + h, y[k] + h * k3)
y[k + 1] = y[k] + (1/6)*h*(k1 + 2*k2 + 2*k3 + k4)
x += h

return y


if __name__ == "__main__":
import doctest

doctest.testmod()