Last active
August 29, 2015 14:18
-
-
Save samuelsmal/1d8bd4f0c11fd38d61d1 to your computer and use it in GitHub Desktop.
Mathematica Runge-Kutta
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
(* One step Runge-Kutta *) | |
(* fn : Definition of the function *) | |
(* init : List of initial values, dimensions have to agree with the input of fn *) | |
(* step : Step size for the numerical simulation *) | |
(* Usage: *) | |
(* One step: *) | |
(* RungeKutta[{#[[2]], #[[1]]^2 - 2#[[2]]}&,{.1, -.5}, .1] *) | |
(* Multiple steps: *) | |
(* NestList[RungeKutta[{#[[2]], #[[1]]^2 - 2#[[2]]}&, #, 0.1]& , {.1, -.5}, 5] *) | |
RungeKutta[fn_, init_, step_] := Module[ | |
{k1, k2, k3, k4}, | |
k1 = step fn[init]; | |
k2 = step fn[init + k1 / 2]; | |
k3 = step fn[init + k2 / 2]; | |
k4 = step fn[init + k3]; | |
init + Total[{k1, 2 k2, 2 k3, k4}]/6 | |
] |
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
stepSize = 0.0004; | |
initialValues = {2.12, -3.1}; | |
vanDerPolParam = 5; | |
nrIterations = 100000; | |
vanDerPol := {#[[2]], #2 (1 - #[[1]]^2) #[[2]] - #[[1]]} & | |
RungeKutta[fn_, init_, step_] := Module[ | |
{k1, k2, k3, k4}, | |
k1 = step fn[init]; | |
k2 = step fn[init + k1 / 2]; | |
k3 = step fn[init + k2 / 2]; | |
k4 = step fn[init + k3]; | |
init + Total[{k1, 2 k2, 2 k3, k4}]/6 | |
] | |
ListPlot[NestList[ | |
RungeKutta[(vanDerPol[#, vanDerPolParam]) &, #, stepSize] & , | |
initialValues, nrIterations], | |
Frame -> True, | |
Axes -> None, | |
AspectRatio -> 1, | |
PlotRange -> All]1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment