Created
February 21, 2019 05:31
-
-
Save soeirosantos/39a17dbe3cf122db4dd61748139796ca to your computer and use it in GitHub Desktop.
Runge-Kutta 2nd and 4th order comparison
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Numerical methods for ordinary differential equations are | |
methods used to find numerical approximations to the solutions | |
of ordinary differential equations (ODEs). Their use is also | |
known as "numerical integration", although this term is sometimes | |
taken to mean the computation of integrals. | |
The Runge–Kutta methods are a family of implicit and explicit | |
iterative methods used in temporal discretization for the approximate | |
solutions of ordinary differential equations. | |
In this example we are comparing the Runge-Kutta methods 2nd and 4th | |
orders with the analytical solution. The purpose is to compare the | |
efficience of the methods in terms of approximation and, of course, | |
conclude that the 4th order is much more efficient. | |
More details: http://mathworld.wolfram.com/Runge-KuttaMethod.html | |
''' | |
def runge_kutta2(f, x, y, h): | |
k1 = f(x, y) | |
k2 = f(x + h, y + h * k1) | |
return y + h/2 * (k1 + k2) | |
def runge_kutta4(f, x, y, h): | |
k1 = f(x, y) | |
k2 = f(x + h / 2, y + h/2 * k1) | |
k3 = f(x + h / 2, y + h/2 * k2) | |
k4 = f(x + h, y + h * k3) | |
return y + h/6 * (k1 + 2 * k2 + 2 * k3 + k4) | |
if __name__ == "__main__": | |
import math | |
''' | |
IVP | |
y' = y, | |
y(0) = 1 | |
''' | |
def f(x, y): | |
return y | |
y0 = 1 | |
h = 0.04 | |
xn = 0.04 | |
yn_1 = runge_kutta2(f, xn, y0, h) | |
error = math.exp(xn) - yn_1 | |
print("Runge-Kutta 2nd order: %s" % yn_1) | |
print("Runge-Kutta 2nd order error: %s" % error) | |
yn_1 = runge_kutta4(f, xn, y0, h) | |
error = math.exp(xn) - yn_1 | |
print("Runge-Kutta 4th order: %s" % yn_1) | |
print("Runge-Kutta 4th order error: %s" % error) | |
''' | |
output: | |
Runge-Kutta 2nd order: 1.0408 | |
Runge-Kutta 2nd order error: 1.077419238826316e-05 | |
Runge-Kutta 4th order: 1.0408107733333334 | |
Runge-Kutta 4th order error: 8.590548272735532e-10 | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment