The following is a sample javascript implementation of the Rünge-Kutta method of numerically solving initial value problems in ordinary differential equations. In particular, this webpage implements the so-called RK4 method which is a 4th order method.

Example

Consider the equation y'=f(x,y)=yx2 - 6*y/5. Given an initial value y(0)=y0, we want to know the approximate value of the function y(x) when x=x1.

Enter values for y0 and x1 and a number of iterations of RK4 to use to approximate y1=y(x1).

Number of Iterations (n):
Initial Value (y0):
Target (x1):
<script type="text/javascript"> var g2 =[]; function f(x,y) { // return the value of y' return Math.pow(x,2)*y - 6*y/5; } function g(x) { // the is the return Math.exp(-6*x/5+Math.pow(x,3)/3); } function rk4iter(x,y,h) { // compute the four RK coefficients using the RHS of the diff eq. k1 = f(x,y); k2 = f(x + h/2, y + k1 * h / 2); k3 = f(x + h/2, y + k2 * h / 2); k4 = f(x + h, y + k3 * h); // compute the y value at the end of the iteration return y + (k1 + 2*k2 + 2*k3 + k4) * h / 6; } function rk4(n,y0,x1) { var h = x1/n; // compute the step size along the x-axis var x = 0; // initial value of x is 0 var y = (+y0); // initial value of y is y0 g2 = [[x,y]]; // start with initial conditions // Prepare the output for reporting var msg = '<table border="0.5"><tr><td width="150">x</td><td width="200">y</td></tr>'; msg += '<tr><td>'+x+'</td><td>'+y+'</td></tr>'; // loop until x reaches its target value for (var i = 1; i <= n; i++) { // Perform iterations of the RK4 algorithm y = rk4iter(x,y,h); x += h; // record the x and y values for this iteration msg += '<tr><td>'+x+'</td><td>'+y+'</td></tr>'; // Add data to the plot as well. g2.push([x,y]); } // record the actual target value, the absolute and percent error msg += '<tr><td>Actual f('+x1+')=</td><td>'+g(x1)+'</td></tr>'; msg += '<tr><td>Absolute Error</td><td>'+Math.abs(g(x1)-y)+'</td></tr>'; msg += '<tr><td>Percent Error</td><td>'+Math.abs(Math.round((g(x1)-y)/g(x1)*1000000))/10000+'%</td></tr>'; // report the target value to the user document.getElementById("msg").innerHTML=msg+'</table>'; // Refresh the plot $(function () { var d1 = []; for (var i = 0; i <= 40; i++) d1.push([i/20, g(i/20)]); $.plot($("#placeholder"), [ { label: "actual", data: d1} , { label: "RK4", data: g2, points: {show: true}}]); }); } </script>