Skip to content
Tutorials Center
My learning

Topics

Lesson 83 of 135 ยท Standard Library

Complex Numbers with complex.h

Use complex numbers in C with complex.h - the double complex type, the I constant, creal, cimag, cabs, carg, cexp and csqrt, plus quadratic roots, DFT and fractals.

A complex number has two parts: a real part and an imaginary part, written 3 + 4i, where i is the square root of -1. They look like a mathematician's toy, but engineers use them every day. Signal processing, electrical circuits, control systems, quantum simulation, fractals and the roots of polynomials are all natural in complex arithmetic. C has supported complex numbers as a built-in type since C99, so you can add, multiply and divide them with the ordinary operators, and the standard library ships a full set of complex functions.

In this lesson you will declare complex variables, use the constant I and the CMPLX macro, read the parts of a number, switch between rectangular and polar form, use the complex versions of exp, sqrt and friends, and put it all to work: solving quadratic equations, transforming a signal and drawing the Mandelbrot set. You should know the real math library and floating-point basics first, because every complex function builds on them.

Types and the constant I

Include <complex.h>. It defines the macro complex as a shorthand for the keyword _Complex, and the constant I, the imaginary unit. A complex type is made from a real floating-point type:

Type Parts are
float complex two floats
double complex two doubles
long double complex two long doubles

So a double complex takes 16 bytes: the real part followed by the imaginary part, in memory just like double[2]. You build values with I:

C
double complex z = 3.0 + 4.0 * I;   // 3 + 4i
double complex w = 2.5;             // a real number is a complex number with imaginary part 0

Link the program with the math library (-lm on Linux), because most complex functions live in it.

Complex arithmetic uses the normal operators. +, -, * and / follow the mathematical rules, including i * i == -1. Compare with == and != only; there is no ordering of complex numbers, so < is a compile error. As with all floating-point values, exact equality is rarely what you want after any calculation (see floating-point numbers).

Reading the parts of a number

Five functions pull a number apart (add an f suffix for float complex or an l for long double complex, such as crealf):

Function Result For 3 + 4i
creal(z) real part 3
cimag(z) imaginary part 4
cabs(z) magnitude (distance from zero) 5
carg(z) argument, the angle in radians, from -pi to pi 0.9273
conj(z) complex conjugate (flip the sign of the imaginary part) 3 - 4i

cabs is computed the careful way (like hypot), so it does not overflow for large parts the way sqrt(re*re + im*im) could.

The printf family has no conversion for complex numbers, so you print the two parts yourself. A helper function keeps this tidy:

C Arithmetic and the parts of a complex number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

You can check the product by hand: (3 + 4i)(1 - 2i) = 3 - 6i + 4i - 8i^2 = 11 - 2i. The quotient a / b is -1 + 2i, and multiplying it back by b gives a again.

CMPLX versus x + y * I

There are two ways to build a number from two variables:

C
double complex z1 = x + y * I;
double complex z2 = CMPLX(x, y);     // C11

For ordinary numbers they are identical. They differ for special values. y * I is a multiplication, and multiplying infinity by I (which is 0 + 1i) computes infinity * 0, which is NaN. So 1.0 + INFINITY * I has a NaN real part (it prints as -nan on this runner), while CMPLX(1.0, INFINITY) has real part 1 and imaginary part infinity exactly as written. CMPLX also states the signed zero in CMPLX(-4.0, -0.0) directly, without relying on how an expression is evaluated. Use CMPLX (and CMPLXF, CMPLXL) when the inputs can be infinite, NaN or negative zero. x + y * I is fine and more readable for everyday values.

Two name warnings: I is a macro, so you cannot also use I as a variable name (int I = 0; will not compile when <complex.h> is included), and complex is a macro too. If you need those identifiers, write #undef I or use _Complex directly. Mathematicians' habit of calling loop counters I is a common source of baffling errors; use i and j.

Polar form and Euler's formula

Every complex number can be described in two ways.

  • Rectangular: real and imaginary parts, x + yi.
  • Polar: a magnitude r and an angle theta, written r * e^(i*theta).
flowchart LR
    A["rectangular<br/>x + y i"] -->|"cabs, carg"| B["polar<br/>r and theta"]
    B -->|"r * cexp(I * theta)"| A

Convert to polar with cabs and carg. Convert back with cexp, which implements Euler's formula e^(i*theta) = cos(theta) + i sin(theta).

Polar form makes multiplication easy: magnitudes multiply and angles add. It also explains the famous identity e^(i*pi) = -1, which you can check on a computer:

C Polar form, Euler's formula and roots of unity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The six numbers printed in the loop are the solutions of x^6 = 1. A real equation of degree 6 has at most two real solutions (1 and -1), but over the complex numbers it has exactly six, evenly spaced on the unit circle.

The complex math functions

Almost every function from <math.h> has a complex twin whose name starts with c:

Group Functions
Powers and roots csqrt, cpow(z, w)
Exponential and logarithm cexp, clog (natural log)
Trigonometry csin, ccos, ctan, casin, cacos, catan
Hyperbolic csinh, ccosh, ctanh, casinh, cacosh, catanh
Parts creal, cimag, cabs, carg, conj, cproj

Each comes in three flavors: csqrt for double complex, csqrtf for float complex and csqrtl for long double complex. The real parameter version cannot return a complex answer, which is why sqrt(-4.0) is NaN but csqrt(-4.0) is 2i: the argument is converted to a complex value with imaginary part zero.

Because sqrt, log and other functions have more than one valid answer in the complex plane (both 2i and -2i square to -4), the library returns a principal value and defines a branch cut where the result jumps. For csqrt and clog the cut lies along the negative real axis, and the sign of a zero imaginary part decides which side you are on. That is exactly where signed zero matters:

C Quadratic equations and branch cuts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first two equations give real answers (with a zero imaginary part), and the third has the conjugate pair -1 + 2i and -1 - 2i. Complex roots of real polynomials always come in conjugate pairs. With the branch cut, -4 + 0i has the square root 2i and -4 - 0i has -2i, a sudden jump that follows the sign of the zero. If you need this level of control, build values with CMPLX, as shown above. clog(-1) is 0 + pi*i, the principal logarithm, which is another way to write Euler's identity.

A complete example: the discrete Fourier transform

The discrete Fourier transform (DFT) turns a list of samples into a list of frequencies. Each output X[k] is a sum of the samples multiplied by rotating complex numbers:

X[k] = sum over n of x[n] * e^(-2*pi*i*k*n/N)

In C that is two nested loops and one cexp. We feed it eight samples of a cosine wave that completes exactly one cycle, so all the energy must land in frequency bin 1, plus its mirror image in bin 7:

C A discrete Fourier transform

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Bins 1 and 7 each hold magnitude 4 (half of the 8 samples) and every other bin is zero. Real programs use the faster FFT algorithm, which computes the same numbers in N log N steps instead of N^2, but the complex arithmetic is identical.

Drawing the Mandelbrot set

The Mandelbrot set is defined with complex numbers: take a point c and repeat z = z*z + c, starting from z = 0. If z stays bounded (cabs(z) <= 2) after many steps, c belongs to the set. In C the iteration is one line:

C The Mandelbrot set in text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Dense @ characters mark points that never escaped. Points outside the set get lighter shades the longer they stayed close to the origin.

Practical notes

  • Complex arithmetic follows IEEE rules for infinities and NaN, but -ffast-math can break this; avoid that flag with complex code.
  • Passing a double complex to a function that expects double * pairs is possible because of the guaranteed layout (double[2]), but prefer creal/cimag.
  • A float complex is half the size and often twice as fast to process in bulk; use it for large arrays of samples when its precision (about 7 digits) is enough.
  • Some compilers (notably Microsoft's cl) do not support C99 _Complex and provide their own _Dcomplex types instead. GCC and Clang support the standard types on all platforms.
  • If a function should work for several complex types, see _Generic and Type-Generic Macros; the <tgmath.h> header does that for the whole math library.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which declaration creates the complex number 2 + 5i?

    <complex.h> provides the macro complex and the constant I, so 2.0 + 5.0 * I builds the value. There is no i suffix in C.
  2. 2. What does cabs(3.0 + 4.0 * I) return?

    cabs is the magnitude, sqrt(33 + 44) = 5.
  3. 3. Why does csqrt(-4.0) return 2i while sqrt(-4.0) returns NaN?

    The real sqrt has no complex results to return, so it reports a domain error as NaN. csqrt works in the complex plane and returns the principal root.
  4. 4. When is CMPLX(x, y) preferable to x + y * I?

    Multiplying by I can turn an infinite or NaN y into NaN in the real part, and can lose a negative zero. CMPLX copies both parts exactly.
  5. 5. Which operator pair is not allowed on complex numbers?

    Complex numbers have no natural ordering, so relational operators are rejected. Equality comparison is allowed.

Summary

  • Include <complex.h> and declare float complex, double complex or long double complex; link with -lm.
  • I is the imaginary unit and CMPLX(re, im) builds a number from two parts exactly; do not name your own variables I or complex.
  • + - * / work directly; == and != exist but ordering operators do not.
  • creal, cimag, cabs, carg, conj take a number apart; r * cexp(I * theta) converts polar form back to rectangular.
  • Functions such as csqrt, cexp, clog, cpow, csin return principal values; the sign of a zero imaginary part decides the side of a branch cut.
  • printf has no complex format, so print the real and imaginary parts separately.

Next: Linked Lists