January 4, 2015 10:11 pm

Thought I'd start off the New Year with a simple freebie, a 4th Order Runge-Kutta class for Delphi, Windows and Mac OS. Should also work on Android and iOS mobile platforms and with Free Pascal. The code below shows how you'd use it. First declare the set of differential equations that need to be solved (TDoubleDynArray type can be found in Types):

TMySystem = class (TObject) class procedure func (time : double; y, p, dydt : TDoubleDynArray); end; class procedure TMySystem.func (time : double; y, p, dydt : TDoubleDynArray); begin dydt[0] := p[0] - p[1]*y[0]; dydt[1] := p[1]*y[0] - p[2]*y[1]; end;

Next, create a Runge-Kutta object:

// First argument = number of ODEs // Second argument = number of parameters, if any // Third argument = ODE Function rk4 := TRK4.Create (2, 3, TMySystem.func); rk4.p[0] := vo; rk4.p[1] := k1; rk4.p[2] := k2;

The above code include the option to declare and initialize some parameters that are part of the differential equations. To actually integrate the system by one step use the line:

// Return new time point, assign to startTime ready for next time startTime := rk4.eval (startTime, y, stepSize);

The y argument will contain the updated solution. Run the line again to do the next step etc. Note that the eval method takes three arguments, that current value for the independent variable (time), an array that contains the current values for the dependent variable, and the step size to use.

Download the code here. RK4.zip The download include a Windows exe that you can try right away.

## No comments:

Post a Comment