RK4 – Runge Kutta order 4 integrator

If you are a fellow game developer you probably heard or even implemented and used the RK4 integrator.
For those of you who haven’t here’s a quick info about it.
The Runge Kutta order 4 integrator is like the name says a integrator. You need integrators in games so you can solve differential equations which occur basicly as soon as you implement some physics.
For Example:
You want to calculate the position or velocity of a object in the next frame. The newton mechanics teach us you would do that like this:

So how would you program this?
There are several integrators like the Euler (very common) and the quadric integrator. The Euler integrator is very intuitive.

void update(float dt){

velocity += acceleration * dt;
position += velocity * dt;

}

The problem with this solution is that the Euler integrator has quite a inaccuracy if the rate of change is not constant.
So if your acceleration is constant, you don’t have a problem calculating the velocity (which is not always the case).
But even if the acceleration is constant you will get an inaccuracy when calculating the position in the next line, since velocity changes over time.
And that error will add up every time you update. This can get quite troublesome in a racing simulation for example.
To prevent that inaccuracy you can use the RK4 integrator. It’s not perfect but it’s as accurate as you will ever need it to be in a game.

What the RK4 does is basicly integrating to the fourth derivative and calculating the changes over time. That’s why it’s called order 4.
After that it takes these four sampled derivatives and builds a weighted average of them which gives you a very good approximation to the derivative.

My Euler vs RK4 implementation

Now what really interested me was exactly how different are the Euler and the RK4 integrator in practice.
So I implemented both the Euler and the RK4 integrator in a little project where you can control a spaceship (triangle) with you WASD keys.
As long as I only flew around on the screen there weren’t any differences since the thrustStrength (and therefore acceleration) were fixed.
But then I implemented a spring force which drags the spaceships back to the center of the screen. And that really showed the differences.

The Blue triangle is the Spaceship which gets it’s position integrated by the Euler integrator. The red one uses RK4 (wow that sounds like a bad commercial for toothpaste).
Both get exactly the same input and forces applied. But as you can see the difference is quite relevant.

You can try out the project itself if you want. Download the binary here: http://mwebi.com/stuff/Euler_vs_RK4.zip

If you are interested in the source code you can view it on github: https://github.com/mwebi/EulervsRK4
You will need openframeworks v 0061 and visual studio 2008 to build it.