ZetCode

Complex numbers in Pascal

last modified November 19, 2026 Free Pascal 3.2.2

Pascal has no built-in complex type, but a record with two real fields and a set of overloaded operators gives one that reads like a built-in type. This article starts with the record alone, then adds the operators, the polar form, and two applications. The advanced records article explains the operator syntax in ObjFPC; here the operators are applied to complex arithmetic.

A complex value

A complex number has a real part and an imaginary part. The record below stores them as two Double fields. No operator and no helper is needed to create a value: assign both fields and print them. The format string '+0.00;-0.00' prints a plus sign for positive values and a minus sign for negative ones, so the imaginary part always carries its sign.

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

uses SysUtils;

type
  TComplex = record
    Re, Im: Double;
  end;

var
  Z: TComplex;

begin
  Z.Re := 3;
  Z.Im := 4;
  WriteLn(FormatFloat('0.00', Z.Re), ' ',
    FormatFloat('+0.00;-0.00', Z.Im), 'i');
end.

The number 3 + 4i is stored as Re = 3 and Im = 4. Nothing in the record knows that it represents a complex number; the meaning comes from the functions and operators that the rest of the article adds. A record is a value type, so assigning one complex variable to another copies both fields.

$ fpc -gl complex1.pas
$ ./complex1
3.00 +4.00i

Arithmetic with operators

An operator declaration binds a symbol to a function, so that A + B calls the body written for TComplex. ObjFPC declares these operators at the top level, after the type. The C helper builds a value without two assignments at every call site, and Show keeps the output consistent.

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

uses SysUtils;

type
  TComplex = record
    Re, Im: Double;
  end;

operator + (const A, B: TComplex): TComplex;
begin
  Result.Re := A.Re + B.Re;
  Result.Im := A.Im + B.Im;
end;

operator - (const A, B: TComplex): TComplex;
begin
  Result.Re := A.Re - B.Re;
  Result.Im := A.Im - B.Im;
end;

operator * (const A, B: TComplex): TComplex;
begin
  Result.Re := A.Re * B.Re - A.Im * B.Im;
  Result.Im := A.Re * B.Im + A.Im * B.Re;
end;

function C(Re, Im: Double): TComplex;
begin
  Result.Re := Re;
  Result.Im := Im;
end;

procedure Show(const Name: string; Z: TComplex);
begin
  WriteLn(Name, ' = ', FormatFloat('0.00', Z.Re), ' ',
    FormatFloat('+0.00;-0.00', Z.Im), 'i');
end;

var
  A, B: TComplex;

begin
  A := C(3, 4);
  B := C(1, -2);
  Show('A', A);
  Show('B', B);
  Show('A + B', A + B);
  Show('A - B', A - B);
  Show('A * B', A * B);
end.

Multiplication follows the rule (a + bi)(c + di) = (ac - bd) + (ad + bc)i. With A = 3 + 4i and B = 1 - 2i, the product is 11 - 2i, because the real part is 3·1 - 4·(-2) = 11 and the imaginary part is 3·(-2) + 4·1 = -2. Addition and subtraction work component by component.

$ fpc -gl complex2.pas
$ ./complex2
A = 3.00 +4.00i
B = 1.00 -2.00i
A + B = 4.00 +2.00i
A - B = 2.00 +6.00i
A * B = 11.00 -2.00i

Modulus, argument, and conjugate

The modulus of a complex number is its distance from the origin, and the argument is the angle it makes with the positive real axis. Sqrt(Re² + Im²) computes the modulus, and ArcTan2(Im, Re) computes the argument in the correct quadrant. The conjugate flips the sign of the imaginary part, which reflects the point across the real axis.

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

uses Math, SysUtils;

type
  TComplex = record
    Re, Im: Double;
  end;

function C(Re, Im: Double): TComplex;
begin
  Result.Re := Re;
  Result.Im := Im;
end;

function Modulus(const Z: TComplex): Double;
begin
  Result := Sqrt(Z.Re * Z.Re + Z.Im * Z.Im);
end;

function Argument(const Z: TComplex): Double;
begin
  Result := ArcTan2(Z.Im, Z.Re);
end;

function Conjugate(const Z: TComplex): TComplex;
begin
  Result.Re := Z.Re;
  Result.Im := -Z.Im;
end;

procedure Show(const Name: string; Z: TComplex);
begin
  WriteLn(Name, ' = ', FormatFloat('0.000', Z.Re), ' ',
    FormatFloat('+0.000;-0.000', Z.Im), 'i');
end;

var
  Z: TComplex;
  R, Theta: Double;

begin
  Z := C(3, 4);
  R := Modulus(Z);
  Theta := Argument(Z);
  WriteLn('modulus:  ', FormatFloat('0.000', R));
  WriteLn('argument: ', FormatFloat('0.000', Theta));
  Show('reconstructed', C(R * Cos(Theta), R * Sin(Theta)));
  Show('conjugate', Conjugate(Z));
end.

The modulus of 3 + 4i is 5, the classic 3-4-5 triangle, and the argument is about 0.927 radians, or 53.1 degrees. Rebuilding the value from r cos θ and r sin θ returns 3 + 4i. The conjugate is 3 - 4i. The reconstruction is the bridge between the rectangular form (a + bi) and the polar form (r, θ).

$ fpc -gl polar1.pas
$ ./polar1
modulus:  5.000
argument: 0.927
reconstructed = 3.000 +4.000i
conjugate = 3.000 -4.000i

Division and Euler's formula

Division multiplies the numerator and the denominator by the conjugate of the denominator, which makes the denominator real. Euler's formula connects the polar form to the exponential: eiθ = cos θ + i sin θ. The CExp function evaluates that expression for a general complex exponent.

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

uses Math, SysUtils;

type
  TComplex = record
    Re, Im: Double;
  end;

function C(Re, Im: Double): TComplex;
begin
  Result.Re := Re;
  Result.Im := Im;
end;

operator / (const A, B: TComplex): TComplex;
var
  D: Double;
begin
  D := B.Re * B.Re + B.Im * B.Im;
  Result.Re := (A.Re * B.Re + A.Im * B.Im) / D;
  Result.Im := (A.Im * B.Re - A.Re * B.Im) / D;
end;

function CExp(const Z: TComplex): TComplex;
var
  E: Double;
begin
  E := Exp(Z.Re);
  Result.Re := E * Cos(Z.Im);
  Result.Im := E * Sin(Z.Im);
end;

procedure Show(const Name: string; Z: TComplex);
begin
  WriteLn(Name, ' = ', FormatFloat('0.000', Z.Re), ' ',
    FormatFloat('+0.000;-0.000', Z.Im), 'i');
end;

var
  Z: TComplex;

begin
  Z := C(3, 4);
  WriteLn('division:');
  Show('  Z / (1 - 2i)', Z / C(1, -2));
  WriteLn('Euler:');
  Show('  exp(i*pi)', CExp(C(0, Pi)));
end.

Dividing 3 + 4i by 1 - 2i gives -1 + 2i. Substituting θ = π into Euler's formula gives -1 with a tiny imaginary part, which is the identity eiπ + 1 = 0 up to floating-point rounding. The division operator and the exponential are the last pieces needed for the two applications that follow.

$ fpc -gl polar2.pas
$ ./polar2
division:
  Z / (1 - 2i) = -1.000 +2.000i
Euler:
  exp(i*pi) = -1.000 +0.000i

The Mandelbrot set

The Mandelbrot set contains the complex points c for which the iteration zn+1 = zn² + c, starting from zero, stays bounded. A point is considered outside the set when its modulus exceeds 2, because beyond that value the sequence diverges. The program maps a rectangle of the complex plane onto a character grid and prints a character that depends on how many iterations the point survived.

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

type
  TComplex = record
    Re, Im: Double;
  end;

operator + (const A, B: TComplex): TComplex;
begin
  Result.Re := A.Re + B.Re;
  Result.Im := A.Im + B.Im;
end;

operator * (const A, B: TComplex): TComplex;
begin
  Result.Re := A.Re * B.Re - A.Im * B.Im;
  Result.Im := A.Re * B.Im + A.Im * B.Re;
end;

function C(Re, Im: Double): TComplex;
begin
  Result.Re := Re;
  Result.Im := Im;
end;

function ModulusSq(const Z: TComplex): Double;
begin
  Result := Z.Re * Z.Re + Z.Im * Z.Im;
end;

const
  Width = 60;
  Height = 24;
  MaxIter = 40;
  Chars: array[0..9] of Char = ' .:-=+*#%@';

var
  Row, Col, Iter, Index: Integer;
  Z, Point: TComplex;

begin
  for Row := 0 to Height - 1 do
  begin
    for Col := 0 to Width - 1 do
    begin
      Point := C(-2.2 + (3.0 * Col / (Width - 1)),
                  1.2 - (2.4 * Row / (Height - 1)));
      Z := C(0, 0);
      Iter := 0;
      while (Iter < MaxIter) and (ModulusSq(Z) <= 4.0) do
      begin
        Z := Z * Z + Point;
        Inc(Iter);
      end;
      if Iter = MaxIter then
        Write(Chars[9])
      else
      begin
        Index := Iter mod 10;
        Write(Chars[Index]);
      end;
    end;
    WriteLn;
  end;
end.

Points that never escape are printed with @, the densest character; points that escape after a few iterations get a lighter character from the start of Chars. The cardioid body and the two bulbs are visible in the middle, and the symmetry around the real axis comes from the fact that the set is closed under complex conjugation. Doubling the width and height improves the picture but quadruples the work; the 40-iteration limit is what keeps the interior from being counted exactly.

$ fpc -gl mandelbrot.pas
$ ./mandelbrot
............:::::::::--------------------------:::::::::::::
...........::::::-----------------====+# ++====----:::::::::
..........::::----------------======++*#@-#@+====-----::::::
.........:::---------------=======+++*% +@@%#++====-----::::
........::---------------=======+***#%:@@@@@@#*+++===-----::
.......::--------------=====++*-..@@-.- @@@+: *%##@*==-----:
......:-------------===+++++**#@%@@@@@@@@@@@@@@+#@@:++=-----
......----------==++++++++***%+-@@@@@@@@@@@@@@@@@+.#*+==----
.....:----=====++*@ %#%*%##%%+#@@@@@@@@@@@@@@@@@@@@@%*==----
.....--======+++*#%  @@#*@-..@@@@@@@@@@@@@@@@@@@@@@#%*===---
.....======+++*%%@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%#+===---
....-++*###*#%@ %@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#*+===---
....-++*###*#%@ %@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#*+===---
.....======+++*%%@.@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%#+===---
.....--======+++*#%  @@#*@-..@@@@@@@@@@@@@@@@@@@@@@#%*===---
.....:----=====++*@ %#%*%##%%+#@@@@@@@@@@@@@@@@@@@@@%*==----
......----------==++++++++***%+-@@@@@@@@@@@@@@@@@+.#*+==----
......:-------------===+++++**#@%@@@@@@@@@@@@@@+#@@:++=-----
.......::--------------=====++*-..@@-.- @@@+: *%##@*==-----:
........::---------------=======+***#%:@@@@@@#*+++===-----::
.........:::---------------=======+++*% +@@%#++====-----::::
..........::::----------------======++*#@-#@+====-----::::::
...........::::::-----------------====+# ++====----:::::::::
............:::::::::--------------------------:::::::::::::

A discrete Fourier transform

The discrete Fourier transform takes N samples and computes N complex coefficients, one per frequency bin: Xk = Σ xn · e-2πikn/N. The example uses eight samples of a cosine at the frequency of bin 1. A real cosine of amplitude 1 should produce a magnitude of 4 at bin 1 and at bin 7, and zero elsewhere.

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

uses Math, SysUtils;

type
  TComplex = record
    Re, Im: Double;
  end;

operator + (const A, B: TComplex): TComplex;
begin
  Result.Re := A.Re + B.Re;
  Result.Im := A.Im + B.Im;
end;

function C(Re, Im: Double): TComplex;
begin
  Result.Re := Re;
  Result.Im := Im;
end;

function Modulus(const Z: TComplex): Double;
begin
  Result := Sqrt(Z.Re * Z.Re + Z.Im * Z.Im);
end;

const
  N = 8;

var
  Signal: array[0..N - 1] of Double;
  Sum: TComplex;
  K, T: Integer;
  Angle: Double;

begin
  for T := 0 to N - 1 do
    Signal[T] := Cos(2 * Pi * T / N);

  WriteLn('bin  magnitude');
  for K := 0 to N - 1 do
  begin
    Sum := C(0, 0);
    for T := 0 to N - 1 do
    begin
      Angle := -2 * Pi * K * T / N;
      Sum := Sum + C(Signal[T] * Cos(Angle), Signal[T] * Sin(Angle));
    end;
    WriteLn(K:2, '   ', FormatFloat('0.000', Modulus(Sum)));
  end;
end.

Bins 1 and 7 carry the positive and negative frequency of the same real cosine, each with magnitude 4, and the other bins are zero to three decimal places. The pair is a consequence of the input being real: the spectrum is conjugate symmetric, so XN-k is the conjugate of Xk. The loop evaluates the exponential directly with Cos and Sin; a fast Fourier transform computes the same result in N log N operations instead of N².

$ fpc -gl dft.pas
$ ./dft
bin  magnitude
 0   0.000
 1   4.000
 2   0.000
 3   0.000
 4   0.000
 5   0.000
 6   0.000
 7   4.000

Next steps

The advanced records article explains the top-level operator declarations and the alternative class operator form in Delphi mode. The linear algebra article uses arrays of reals for its matrices, and the numerical integration article passes functions as parameters. The big integers article shows another custom numeric type built from a record and operators.

Source

Free Pascal Reference guide: operator overloading

Complex number on Wikipedia

Discrete Fourier transform on Wikipedia

In this article we stored a complex value in a record, overloaded addition, subtraction, multiplication, and division, computed the modulus, argument, and conjugate, reconstructed the polar form, drew the Mandelbrot set, and computed a discrete Fourier transform. The series continues with numerical integration and root finding in Pascal.

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.