Game Development Reference
In-Depth Information
public class ODESolver
{
// Fourth-order Runge-Kutta ODE solver.
public static void rungeKutta4(ODE ode, double ds) {
// Define some convenience variables to make the
// code more readable
int j;
int numEqns = ode.getNumEqns();
double s;
double q[];
double dq1[] = new double[numEqns];
double dq2[] = new double[numEqns];
double dq3[] = new double[numEqns];
double dq4[] = new double[numEqns];
// Retrieve the current values of the dependent
// and independent variables.
s = ode.getS(); // independent variable
q = ode.getAllQ(); // dependent variables
The method computes the four estimates for Δ
q
according to Equations (4.23a) through
(4.23d) by calling the
getRightHandSide
method on the
ODE
object. The arguments to the
getRightHandSide
method define where the dependent and independent variables are evalu-
ated for each step (
q
n
+ 1/2Δ
q
1
, for example).
// Compute the four Runge-Kutta steps. The return
// value of getRightHandSide method is an array of
// delta-q values for each of the four steps.
dq1 = ode.getRightHandSide(s, q, q, ds, 0.0);
dq2 = ode.getRightHandSide(s+0.5*ds, q, dq1, ds, 0.5);
dq3 = ode.getRightHandSide(s+0.5*ds, q, dq2, ds, 0.5);
dq4 = ode.getRightHandSide(s+ds, q, dq3, ds, 1.0);
q
have been computed, the update to the dependent variables
can be calculated according to Equation (4.23e). The value of the independent variable,
s
, is
incremented to its new value.
Once the four estimates for
Δ
// Update the dependent and independent variable values
// at the new dependent variable location and store the
// values in the ODE object arrays.
ode.setS(s+ds);