Lore Michael Lones

Generating the Lorenz Attractor using Java and Apache Commons

This is a short example of how to use the Apache Commons Maths package to numerically integrate Lorenz's differential equations (i.e. generate the Lorenz attractor). You can download the maths package here and read the documentation here (although there is some discrepency between the two!). Whilst this example uses the Runge-Kutta method, the maths library also provides a selection of other numerical integration methods.


import org.apache.commons.math.ode.*;

public class Lorenz implements FixedStepHandler {

 
public static void main(String[] args) {
   
new Lorenz();
 
}
 
 
public Lorenz() {
   
LorenzEquations equations = new LorenzEquations(10, 28, 8/3);
   
   
// using fourth-order Runge-Kutta numerical integration with time step of 0.001
   
ClassicalRungeKuttaIntegrator integrator = new ClassicalRungeKuttaIntegrator(0.001);
   
   
// output results every 0.01 time steps
   
integrator.setStepHandler(new StepNormalizer(0.01, this));
   
   
// run integrator
   
try {
     
integrator.integrate(equations,
         
0,              // start time
         
new double[]{10,-2,50},    // initial conditions
         
100,            // end time
         
new double[3]);        // storage
   
} catch (DerivativeException e) {
     
e.printStackTrace();
   
} catch (IntegratorException e) {
     
e.printStackTrace();
   
}
  }
 
 
public class LorenzEquations implements FirstOrderDifferentialEquations {

   
public double prandtl;    // d
   
public double rayleigh;    // p
   
public double beta;      // B
   
   
public LorenzEquations(double d, double p, double B) {
     
this.prandtl = d;
     
this.rayleigh = p;
     
this.beta = B;
   
}
   
   
public void computeDerivatives(double t, double[] y, double[] yDot)
       
throws DerivativeException {
     
yDot[0] = prandtl * (y[1]-y[0]);        // dx/dt = d(y-x)
     
yDot[1] = y[0] * (rayleigh - y[2]) - y[1];    // dy/dt = x(p-z)-y
     
yDot[2] = y[0] * y[1] - beta * y[2];      // dz/dt = xy - Bz
   
}

   
public int getDimension() {
     
return 3;
   
}
   
  }

 
// called by the integrator (via StepNormalizer) after each time step
 
public void handleStep(double t, double[] y, boolean isLast) {
   
System.out.println(""+t+"\t"+y[0]+"\t"+y[1]+"\t"+y[2]);
 
}

}
These web pages use Google Analytics to track visits. See Privacy Statement.
© Michael Lones 2005-2016. Page last updated 30th October, 2013.