License Public Domain
Lines 20
Keywords
numerical computing (8) numerical ODE (1) numerics (5) ODE (1) Runge Kutta (1)
Permissions
Owner: Stou S.
Viewable by Everyone
Editable by All Siafoo Users
Hide
Siafoo is here to make coding less frustrating and to save you time. Join Siafoo Now or Learn More

Runge Kutta 4 Atom Feed 0

In Brief Use it something like this:... more
# 's
 1/*
2 * RungeKutta.hpp
3 *
4 * Created on: Oct 15, 2009
5 * Author: stou@icapsid.net
6 * License: Public Domain (but do send me improvements)
7 */
8
9#include <valarray>
10
11template<typename T, typename F> void RungeKutta4(F f, T t_0, T y_0, T h, std::valarray<T> &t, std::valarray<T> &y){
12
13 y[0] = y_0;
14 t[0] = t_0;
15
16 for(unsigned int i = 0; i < y.size() - 1; ++i){
17
18 T k_1 = f(t[i], y[i]);
19 T k_2 = f(t[i] + 0.5 * h, y[i] + 0.5 * h * k_1);
20 T k_3 = f(t[i] + 0.5 * h, y[i] + 0.5 * h * k_2);
21 T k_4 = f(t[i] + h, y[i] + h * k_3);
22
23 t[i+1] = t[i] + h;
24 y[i+1] = y[i] + (1./6.) * h * (k_1 + T(2) * k_2 + T(2) * k_3 + k_4);
25 }
26}

Use it something like this:

# 's
 1struct ParticleDrop{
2
3 double v_0;
4
5 ParticleDrop(double v = 0.0)
6 : v_0(v) { }
7
8 double operator()(double t, double y) {
9 return v_0 - 9.81 * t;
10 }
11};
12
13const unsigned int steps = 40;
14valarray<double> t(steps);
15valarray<double> y(steps);
16
17RungeKutta4<double, ParticleDrop>(ParticleDrop(), 0, 100.0, 0.1, t, y);

Warning

The code has not been tested very well so be careful when using it.