ZetCode

Scientific simulations in Pascal

last modified November 19, 2026 Free Pascal 3.2.2

A simulation is a loop that advances a model in small steps and records the state. Pascal is well suited to the work: arrays hold the state, procedures hold the update rule, and the compiler produces fast native code without a run-time environment. This article starts with the neighbour rule of Conway's Game of Life, then runs the full automaton, the one-dimensional heat equation, a planetary orbit with the velocity Verlet integrator, a comparison of Euler and Runge-Kutta, and a random walk.

The Game of Life rule

The Game of Life is a cellular automaton on a rectangular grid. Each cell is alive or dead, and the next generation depends on the eight neighbours: a live cell survives with two or three neighbours, a dead cell becomes alive with exactly three. Before writing the whole simulation, the next program applies that rule to the centre of a fixed 3×3 grid.

neighbors.pas
program neighbors;
{$mode objfpc}{$H+}

const
  Grid: array[0..2, 0..2] of Boolean = (
    (True,  False, True),
    (False, False, False),
    (False, True,  False));

function Neighbors(R, C: Integer): Integer;
var
  DR, DC, NR, NC: Integer;
begin
  Result := 0;
  for DR := -1 to 1 do
    for DC := -1 to 1 do
      if (DR <> 0) or (DC <> 0) then
      begin
        NR := R + DR;
        NC := C + DC;
        if (NR >= 0) and (NR <= 2) and (NC >= 0) and (NC <= 2) then
          if Grid[NR, NC] then
            Inc(Result);
      end;
end;

var
  N: Integer;

begin
  N := Neighbors(1, 1);
  WriteLn('neighbours of centre: ', N);
  WriteLn('centre alive next:    ', N = 3);
end.

The centre is dead and has three live neighbours, at the top left, top right, and bottom centre, so it becomes alive in the next generation. The two nested loops from -1 to 1 visit the eight surrounding positions and skip the DR = 0, DC = 0 case, which is the cell itself. The bounds check before Grid[NR, NC] keeps the corners and edges safe.

$ fpc -gl neighbors.pas
$ ./neighbors
neighbours of centre: 3
centre alive next:    TRUE

The Game of Life

The full simulation uses a fixed grid with dead borders and starts from a glider, a five-cell pattern that moves one cell diagonally every four generations. Step reads the old grid and writes a separate Next grid, so a cell sees the state of the previous generation even when its neighbours have already been updated.

life.pas
program life;
{$mode objfpc}{$H+}

const
  Rows = 10;
  Cols = 16;
  Generations = 4;

type
  TGrid = array[0..Rows - 1, 0..Cols - 1] of Boolean;

procedure Clear(var G: TGrid);
var
  R, C: Integer;
begin
  for R := 0 to Rows - 1 do
    for C := 0 to Cols - 1 do
      G[R][C] := False;
end;

procedure PrintGrid(const G: TGrid; Gen: Integer);
var
  R, C: Integer;
begin
  WriteLn('generation ', Gen);
  for R := 0 to Rows - 1 do
  begin
    for C := 0 to Cols - 1 do
      if G[R][C] then
        Write('#')
      else
        Write('.');
    WriteLn;
  end;
end;

function Neighbors(const G: TGrid; R, C: Integer): Integer;
var
  DR, DC, NR, NC: Integer;
begin
  Result := 0;
  for DR := -1 to 1 do
    for DC := -1 to 1 do
      if (DR <> 0) or (DC <> 0) then
      begin
        NR := R + DR;
        NC := C + DC;
        if (NR >= 0) and (NR < Rows) and (NC >= 0) and (NC < Cols) then
          if G[NR][NC] then
            Inc(Result);
      end;
end;

procedure Step(const G: TGrid; var Next: TGrid);
var
  R, C, N: Integer;
begin
  for R := 0 to Rows - 1 do
    for C := 0 to Cols - 1 do
    begin
      N := Neighbors(G, R, C);
      if G[R][C] then
        Next[R][C] := (N = 2) or (N = 3)
      else
        Next[R][C] := (N = 3);
    end;
end;

var
  G, Next: TGrid;
  Gen: Integer;

begin
  Clear(G);
  { glider }
  G[1][2] := True;
  G[2][3] := True;
  G[3][1] := True;
  G[3][2] := True;
  G[3][3] := True;

  for Gen := 0 to Generations do
  begin
    PrintGrid(G, Gen);
    if Gen < Generations then
    begin
      Step(G, Next);
      G := Next;
    end;
  end;
end.

Assigning G := Next copies the whole static array, which is only 160 booleans here. Neighbors skips the cell itself and checks the borders before indexing, so no range error is possible. The glider moves one cell down and right every four generations, which is exactly what the five printed grids show.

$ fpc -gl life.pas
$ ./life
generation 0
................
..#.............
...#............
.###............
................
................
................
................
................
................
generation 1
................
................
.#.#............
..##............
..#.............
................
................
................
................
................
generation 2
................
................
...#............
.#.#............
..##............
................
................
................
................
................
generation 3
................
................
..#.............
...##...........
..##............
................
................
................
................
................
generation 4
................
................
...#............
....#...........
..###...........
................
................
................
................
................

The heat equation

The one-dimensional heat equation ∂u/∂t = α ∂²u/∂x² describes how temperature diffuses along a rod. The explicit finite-difference scheme replaces the second derivative with the three-point formula (ui-1 - 2ui + ui+1)/Δx² and advances each interior point by r times that value, where r = α Δt/Δx². The scheme is stable only for r ≤ 0.5; the example uses 0.1.

heat.pas
program heat;
{$mode objfpc}{$H+}

uses SysUtils;

const
  N = 21;
  Steps = 200;
  PrintEvery = 50;
  Alpha = 0.1;
  Dt = 1.0;
  Dx = 1.0;

type
  TField = array[0..N - 1] of Double;

procedure PrintRow(const Title: string; const U: TField);
var
  I: Integer;
begin
  Write(Format('%-8s', [Title]), ':');
  for I := 0 to N - 1 do
    Write(Format('%7.2f', [U[I]]));
  WriteLn;
end;

var
  U, Next: TField;
  I, Step: Integer;
  R: Double;

begin
  for I := 0 to N - 1 do
    U[I] := 0;
  U[N div 2] := 100;
  U[0] := 0;
  U[N - 1] := 0;

  R := Alpha * Dt / (Dx * Dx);
  WriteLn('r = ', FormatFloat('0.00', R));
  PrintRow('step   0', U);

  for Step := 1 to Steps do
  begin
    Next := U;
    for I := 1 to N - 2 do
      Next[I] := U[I] + R * (U[I - 1] - 2 * U[I] + U[I + 1]);
    U := Next;

    if Step mod PrintEvery = 0 then
      PrintRow('step ' + IntToStr(Step), U);
  end;
end.

The initial state is a single hot point of 100 degrees at the centre and zero everywhere else, with the two ends held at zero. After 50 steps the peak has dropped to 12.68 and the heat has spread symmetrically; by step 200 the profile is a smooth bell with a peak of 6.23. The total heat decreases because the fixed zero boundaries absorb it. The assignment Next := U copies the boundaries and the old values, and only the interior is overwritten, which keeps the boundary conditions in place.

$ fpc -gl heat.pas
$ ./heat
r = 0.10
step   0:   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00 100.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00   0.00
step 50 :   0.00   0.19   0.51   1.08   2.07   3.58   5.63   8.02  10.34  12.05  12.68  12.05  10.34   8.02   5.63   3.58   2.07   1.08   0.51   0.19   0.00
step 100:   0.00   0.74   1.55   2.47   3.54   4.73   5.96   7.12   8.08   8.72   8.94   8.72   8.08   7.12   5.96   4.73   3.54   2.47   1.55   0.74   0.00
step 150:   0.00   0.92   1.84   2.78   3.71   4.63   5.47   6.21   6.79   7.15   7.28   7.15   6.79   6.21   5.47   4.63   3.71   2.78   1.84   0.92   0.00
step 200:   0.00   0.90   1.79   2.65   3.47   4.23   4.90   5.46   5.88   6.14   6.23   6.14   5.88   5.46   4.90   4.23   3.47   2.65   1.79   0.90   0.00

An orbit with velocity Verlet

A planet in a circular orbit around a star obeys a = -r/|r|³ in units where the gravitational constant and the star mass are one. The velocity Verlet integrator updates the position with the current velocity and half the acceleration, recomputes the acceleration, and then completes the velocity update. It is symplectic, so the total energy oscillates around the initial value instead of drifting away.

orbit.pas
program orbit;
{$mode objfpc}{$H+}

uses SysUtils, Math;

const
  Dt = 0.001;
  Steps = 6284;

var
  X, Y, VX, VY: Double;
  AX, AY, NAX, NAY, R, E0, E1: Double;
  I: Integer;

procedure Acceleration(PX, PY: Double; out AX, AY: Double);
var
  R3: Double;
begin
  R3 := Power(PX * PX + PY * PY, 1.5);
  AX := -PX / R3;
  AY := -PY / R3;
end;

begin
  X := 1;
  Y := 0;
  VX := 0;
  VY := 1;
  Acceleration(X, Y, AX, AY);
  E0 := 0.5 * (VX * VX + VY * VY) - 1 / Sqrt(X * X + Y * Y);

  for I := 1 to Steps do
  begin
    X := X + VX * Dt + 0.5 * AX * Dt * Dt;
    Y := Y + VY * Dt + 0.5 * AY * Dt * Dt;
    Acceleration(X, Y, NAX, NAY);
    VX := VX + 0.5 * (AX + NAX) * Dt;
    VY := VY + 0.5 * (AY + NAY) * Dt;
    AX := NAX;
    AY := NAY;
  end;

  R := Sqrt(X * X + Y * Y);
  E1 := 0.5 * (VX * VX + VY * VY) - 1 / R;
  WriteLn('radius after one period: ', FormatFloat('0.000000', R));
  WriteLn('energy start: ', FormatFloat('0.0000000000', E0));
  WriteLn('energy end:   ', FormatFloat('0.0000000000', E1));
  WriteLn('drift:        ', FormatFloat('0.00E+00', Abs(E1 - E0)));
end.

A circular orbit at radius 1 has speed 1 and period 2π, so 6284 steps of 0.001 cover one revolution. The radius returns to 1.000000, and the specific energy stays at -0.5 with a drift of 2.22E-15, which is rounding noise. The Power call computes |r|³ as (x² + y²)^1.5; using Sqrt and multiplication would avoid the general power routine, but the clarity is worth the small cost here.

$ fpc -gl orbit.pas
$ ./orbit
radius after one period: 1.000000
energy start: -0.5000000000
energy end:   -0.5000000000
drift:        2.22E-15

Euler versus Runge-Kutta

Euler's method advances yn+1 = yn + h F(tn, yn) and has first-order error, so halving the step halves the error. The classical fourth-order Runge-Kutta method evaluates the derivative at four points inside the step and has fourth-order error, so halving the step reduces the error by a factor of 16. The test equation y' = y, y(0) = 1 has the exact solution e at t = 1.

rk4.pas
program rk4;
{$mode objfpc}{$H+}

uses SysUtils, Math;

function F(T, Y: Double): Double;
begin
  Result := Y;
end;

function Euler(N: Integer): Double;
var
  H, T, Y: Double;
  I: Integer;
begin
  H := 1 / N;
  T := 0;
  Y := 1;
  for I := 1 to N do
  begin
    Y := Y + H * F(T, Y);
    T := T + H;
  end;
  Result := Y;
end;

function RK4(N: Integer): Double;
var
  H, T, Y, K1, K2, K3, K4: Double;
  I: Integer;
begin
  H := 1 / N;
  T := 0;
  Y := 1;
  for I := 1 to N do
  begin
    K1 := F(T, Y);
    K2 := F(T + H / 2, Y + H * K1 / 2);
    K3 := F(T + H / 2, Y + H * K2 / 2);
    K4 := F(T + H, Y + H * K3);
    Y := Y + H * (K1 + 2 * K2 + 2 * K3 + K4) / 6;
    T := T + H;
  end;
  Result := Y;
end;

procedure Report(const Name: string; Value, Exact: Double);
begin
  WriteLn(Name, ': ', FormatFloat('0.000000000000', Value),
    '  error: ', FormatFloat('0.00E+00', Abs(Value - Exact)));
end;

begin
  WriteLn('y'' = y, y(0) = 1, exact y(1) = ', FormatFloat('0.000000000000', Exp(1)));
  Report('euler n=10 ', Euler(10), Exp(1));
  Report('euler n=100', Euler(100), Exp(1));
  Report('rk4   n=10 ', RK4(10), Exp(1));
  Report('rk4   n=100', RK4(100), Exp(1));
end.

Euler with 10 steps has an error of 0.125, and with 100 steps 0.0135, roughly the factor of ten that the first-order method predicts for a tenfold step reduction. RK4 with 10 steps is already accurate to 2.1E-6, and with 100 steps to 2.3E-10. The example uses Exp(1) as the exact value, so the reported error includes the rounding of the reference itself, which is far below the method error in every row.

$ fpc -gl rk4.pas
$ ./rk4
y' = y, y(0) = 1, exact y(1) = 2.718281828459
euler n=10 : 2.593742460100  error: 1.25E-01
euler n=100: 2.704813829422  error: 1.35E-02
rk4   n=10 : 2.718279744135  error: 2.08E-06
rk4   n=100: 2.718281828234  error: 2.25E-10

A random walk

A random walk takes a fixed number of steps in randomly chosen directions. In two dimensions with unit steps along the axes, the mean squared distance from the origin after N steps is exactly N, because the cross-terms average to zero. The simulation runs many walks with a fixed seed and averages the squared distance, which is a simple check of both the generator and the loop.

walk.pas
program walk;
{$mode objfpc}{$H+}

uses SysUtils;

const
  Walks = 2000;
  Steps = 200;

var
  W, S, Dir: Integer;
  X, Y, SumSq: Double;

begin
  RandSeed := 2026;
  SumSq := 0;
  for W := 1 to Walks do
  begin
    X := 0;
    Y := 0;
    for S := 1 to Steps do
    begin
      Dir := Random(4);
      case Dir of
        0: X := X + 1;
        1: X := X - 1;
        2: Y := Y + 1;
        3: Y := Y - 1;
      end;
    end;
    SumSq := SumSq + X * X + Y * Y;
  end;
  WriteLn('walks: ', Walks);
  WriteLn('steps: ', Steps);
  WriteLn('mean squared distance: ', FormatFloat('0.00', SumSq / Walks));
end.

The measured mean squared distance is 196.81, close to the expected 200. The statistical error of the average over 2000 walks is a few units, so the difference is normal. The fixed seed makes the run reproducible; changing RandSeed or calling Randomize gives another sample. The random numbers article explains the generator and the seed in more detail.

$ fpc -gl walk.pas
$ ./walk
walks: 2000
steps: 200
mean squared distance: 196.81

Next steps

The linear algebra article supplies the matrix operations behind implicit and spectral methods, and the numerical integration article covers the root finding and quadrature rules that simulations often need. The floating-point article explains why the energy drift and the tolerance comparisons behave as they do, and the random numbers article covers the statistical side of the walk.

Source

Conway's Game of Life on Wikipedia

Velocity Verlet on Wikipedia

Runge-Kutta methods on Wikipedia

In this article we applied the Game of Life neighbour rule, ran the full automaton, solved the heat equation explicitly, integrated an orbit with velocity Verlet, compared Euler and Runge-Kutta on a known solution, and measured a random walk. The numerical integration and random numbers articles explain the methods behind these simulations in more detail.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.