Lines 20
##### Keywords
numerical ODE (1) numerics (5) ODE (1) Runge Kutta (1)
##### Permissions
Owner: Stou S.
Viewable by Everyone
Editable by All Siafoo Users
Easily highlight source code for your blog with our Syntax Highlighter.

# Runge Kutta 4 0

 In Brief Use it something like this:... more
 Language C++
# '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>1011template<typename T, typename F> void RungeKutta4(F f, T t_0, T y_0, T h, std::valarray<T> &t, std::valarray<T> &y){1213    y[0] = y_0;14    t[0] = t_0;1516    for(unsigned int i = 0; i < y.size() - 1; ++i){1718        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);2223        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};1213const unsigned int steps = 40;14valarray<double> t(steps);15valarray<double> y(steps);1617RungeKutta4<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.