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 := p - p*y; dydt := p*y - p*y; 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 := vo; rk4.p := k1; rk4.p := 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.