Skip to content

Instantly share code, notes, and snippets.

@dk0r
Last active December 14, 2015 13:48
Show Gist options
  • Save dk0r/5096019 to your computer and use it in GitHub Desktop.
Save dk0r/5096019 to your computer and use it in GitHub Desktop.
I would like to test numerical recipe's version 3 (nm3) implementation of runge kutta 4 (rk4).
The example ODE that I would like to test is: 2y'' + 3y' + 5y = 11e^(-x)
initial conditions: y(0)= 7, y'(0)= 13, h = 1/4
I've completed the first rk4() iteration by hand. It is located at the following link:
https://dl.dropbox.com/s/xz7ok9hrwvrjdsj/rk4_ode.pdf?token_hash=AAFIV21CREVvkM8IkvxJ2UusutwnCOW4rwDWsthWCHD_7Q&dl=1
--------------------------------------------------------------------------------------------------------------------
**********I'm interested in the behavior of rk4() w/ different values of "xmin".
When xmin=0, the 1st rk4() iteration outputs: f(0+h)= 9.2 and f'(0+h) = 4.9. These values match my graph of the ODE's solution.
However, if I set xmin=1, then I expect the 1st iteration of rk4() to output f(1+h)~5.8 and f'(1+h)~-8.
Instead the first iteration of rk4() with xmin=1 outputs: f(1+h)~9.2 and f'(1+h)~4.9
Perhaps I am mistaken and f() and f'() are not actually being evaluated at f(xmin + h) and f'(xmin + h).
--------------------------------------------------------------------------------------------------------------------
#include <iostream>
#include <math.h>
#include <nr3.h>
#include <rk4.h>
using namespace std;
void derivs(const Doub x, VecDoub_I & y, VecDoub_O & dydx)
{
dydx[0]= y[1];
dydx[1]= ( 11*exp((-1)*x) - 3*y[1] - 5*y[0] ) / 2;
}
int main (int argc, char * const argv[])
{
VecDoub y(2),dydx(2);
Doub x, xmin, xmax, kmax=9, h=0.25;
VecDoub yout(2);
int k;
xmin=1;
xmax=2; //appears to do nothing
y[0]=7;
y[1]=13;
derivs(xmin,y,dydx);
for(k=0;k<kmax;k++)
{
x=xmin+k*h;
rk4(y, dydx, x, h, yout, derivs);
cout << yout[0] << " " << yout[1] << endl;
// cout << x << " " << yout[0] << " " << yout[1] << endl;
y[0]=yout[0];
y[1]=yout[1];
derivs(x,y,dydx);
}
}
------OUTPUT for xmin=1
9.21384 4.95654
9.63512 -1.27912
8.75132 -5.46765
7.06951 -7.69549
5.04411 -8.27749
3.03421 -7.64435
1.28659 -6.25038
-0.0613032 -4.50732
-0.965235 -2.74425
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment